奇数和偶数(使用 & 或 %) [英] Odd and Even numbers (using & or %)

查看:91
本文介绍了奇数和偶数(使用 & 或 %)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直使用以下方法来查找偶数和奇数:

I've always used the following in order to find even and odd numbers:

if(   $num % 2  ) { echo "odd"; }
if( !($num % 2) ) { echo "even"; }

但最近我偶然发现了以下代码,它们的工作原理完全相同:

But recently I stumbled upon with the following code that works exactly the same:

if(   $num & 1  ) { echo "odd"; }
if( !($num & 1) ) { echo "even; }

&"背后的逻辑是什么在第二种方法中?

What's the logic behind the "&" in the second method?

我去检查了PHP:算术运算符和&符号不是选项的一部分.

I went to check the PHP: Arithmetic Operators and the ampersand is not part of the options.

谢谢.

推荐答案

这是bitwise-AND 运算符.请记住,在计算机中,每个整数都是以二进制形式存储的,最低有效二进制位是 2^0 == 1.因此,每个奇数的最低二进制位 = 1.

It is the bitwise-AND operator. Remember that in the computer, every integer is stored in binary form, and the lowest-significance binary digit is 2^0 == 1. So, every odd number will have the lowest binary digit = 1.

因此,按位 AND 运算符将您的值与常量 1 逐位比较.两个操作数中1的位在结果中设置为1,但任一中的0位结果中的操作数设置为 0.最终结果(将是 10)被 PHP 强制为布尔值,因为您将它用作 if() 中的子句代码> 语句.

So, the bitwise AND operator compares your value bit-by-bit with the constant 1. Bits that are 1 in both operands are set to 1 in the result, but bits that are 0 in either operand are set to 0 in the result. The final result (which will be either 1 or 0) is coerced to boolean by PHP because you are using it as the clause in an if() statement.

使用 & 而不是 % 来检查均匀性有一个很好的理由:速度!% 运算符需要除法运算才能计算余数,这在计算上比直接比较位要昂贵得多.

There is a very good reason for checking evenness with & instead of %: Speed! The % operator requires a division operation so the remainder can be calculated, which is computationally much, much more expensive than just comparing the bits directly.

示例:

$num = 9;                // 9 == 8 + 1 == 2^3 + 2^0 == 1001b
echo (string)($num & 1); // 1001b & 0001b = 0001b - prints '1'

$num = 10;               // 10 == 8 + 2 == 2^3 + 2^1 == 1010b
echo (string)($num & 1); // 1010b & 0001b = 0000b - prints '0'

这篇关于奇数和偶数(使用 & 或 %)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆