The content of this article is about PHP using bit operations to implement addition, subtraction, multiplication and division of integers and testing (code examples). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you. help.
>= 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
Related recommendations:
Code for simple interaction between PHP and html forms
phpHow to generate classes for HTML files? How to generate html file class in php
The above is the detailed content of PHP uses bit operations to implement addition, subtraction, multiplication and division of integers and test them (code example). For more information, please follow other related articles on the PHP Chinese website!