本篇文章给大家带来的内容是关于php使用位运算实现整数的加减乘除并测试(代码示例),有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。
>= 1;
}
return $res;
}
private static function isNegative(int $n) : bool {
return $n < 0;
}
/**
* a/b a = MIN_INTEGER, b!=MIN_INTEGER ?
* @param int $a
* @param int $b
* @return int
*/
private static function p(int $a, int $b) : int {
$x = self::isNegative($a) ? self::negateNumber($a) : $a;
$y = self::isNegative($b) ? self::negateNumber($b) : $b;
$res = 0;
for ($i = 31; $i >-1; $i = self::minus($i, 1)) {
if (($x >> $i)>=$y) {
$res |= (1 << $i);
$x = self::minus($x, $y<<$i);
}
}
return self::isNegative($a) ^ self::isNegative($b) ? self::negateNumber($res):$res;
}
/**
* @param int $a
* @param int $b
* @return int $a / $b
*/
public static function pide(int $a, int $b) : int {
if ($b === 0) {
throw new RuntimeException("pisor is 0");
}
if ($a === self::MIN_INTEGER && $b === self::MIN_INTEGER) {
return 1;
} else if ($b === self::MIN_INTEGER) {
return 0;
} else if ($a === self::MIN_INTEGER) {
$res = self::p(self::add($a, 1), $b);
return self::add($res, self::p(self::minus($a, self::multiple($res, $b)), $b));
} else {
return self::p($a, $b);
}
}
}TEST:
echo Arithmetic::add(1, 2).PHP_EOL; // 3 echo Arithmetic::minus(10, 3).PHP_EOL; // 7 echo Arithmetic::multiple(5, 3).PHP_EOL; // 15 echo Arithmetic::pide(-2147483648, 1).PHP_EOL; // -2147483648 echo Arithmetic::pide(-15, 3).PHP_EOL; // -5
相关推荐:
php如何生成HTML文件的类?php生成html文件类的方法
立即学习“PHP免费学习笔记(深入)”;











