您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

php使用位运算实现整数的加减乘除并测试(代码示例)

2024/2/26 18:26:21发布11次查看
本篇文章给大家带来的内容是关于php使用位运算实现整数的加减乘除并测试(代码示例),有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。
<?php/** * created by phpstorm. * user: mch * date: 8/10/18 * time: 23:51 * 只用位运算不用算数运算实现整数的 + - * / */class arithmetic { const max_integer = 2147483647; const min_integer = -2147483648; /** * @param int $a * @param int $b * @return int $a + $b; */ public static function add(int $a, int $b) : int { $sum = $a; while ($b) { $sum = $a ^ $b; // 不考虑进位 $b = ($a & $b) << 1; // 只考虑进位 $a = $sum; } return $sum; } /** * 相反数 <= 二进制表达取反+1(补码) * @param int $n * @return int */ private static function negatenumber(int $n) : int { return self::add(~$n, 1); } /** * a-b = a + (-b) * @param int $a * @param int $b * @return int */ public static function minus(int $a, int $b) : int { return self::add($a, self::negatenumber($b)); } /** * @param int $a * @param int $b * @return int $a * $b */ public static function multiple(int $a, int $b) : int { $res = 0; while ($b) { if (($b & 1)) { $res = self::add($res, $a); } $a <<= 1; $b >>= 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; // 3echo arithmetic::minus(10, 3).php_eol; // 7echo arithmetic::multiple(5, 3).php_eol; // 15echo arithmetic::pide(-2147483648, 1).php_eol; // -2147483648echo arithmetic::pide(-15, 3).php_eol; // -5
相关推荐:
php和html表单之间实现简单交互的代码
php如何生成html文件的类?php生成html文件类的方法
以上就是php使用位运算实现整数的加减乘除并测试(代码示例)的详细内容。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product