奇数和偶数(使用 & 或 %) [英] Odd and Even numbers (using & or %)
问题描述
我一直使用以下方法来查找偶数和奇数:
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
.最终结果(将是 1
或 0
)被 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屋!