Odd and Even numbers (using & or %)

╄→гoц情女王★ 提交于 2021-02-18 12:14:06

问题


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?

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

Thanks.


回答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.

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.

An example:

$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'



回答2:


& is the binary AND.

The binary value of an odd number AND 1 will be 1, and the binary value of an even number AND 1 will be 0.

This happens because the binary value of an odd number always ends with 1 and the binary value of an even number ends with 0. So...

10101101 & 00000001 = 00000001 in the case of an odd number and,

10101100 & 00000000 = 00000000 in the case of an even number.



来源:https://stackoverflow.com/questions/17175947/odd-and-even-numbers-using-or

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!