@@ -45,7 +45,7 @@ All those introduced operators are instant (same speed as an addition) on a CPU
4545
4646### Bitwise operators
4747
48- - & : The bitwise AND operator compares each bit of its first operand with the corresponding bit of its second operand.
48+ - $ \& $ : The bitwise AND operator compares each bit of its first operand with the corresponding bit of its second operand.
4949 If both bits are 1, the corresponding result bit is set to 1. Otherwise, the corresponding result bit is set to 0.
5050
5151- $|$ : The bitwise inclusive OR operator compares each bit of its first operand with the corresponding bit of its second operand.
@@ -126,16 +126,19 @@ bool is_set(unsigned int number, int x) {
126126
127127### Check if the number is divisible by a power of 2
128128
129- - Using the and operation, we can check if a number x is even because x & 1 = 0 if x is even, and x & 1 = 1 if x is odd.
130- More generally, x is divisible by $2^{k}$ exactly when x & ($ 2^{k}$ − 1) = 0.
129+ Using the and operation, we can check if a number $n$ is even because $n ~\&~ 1 = 0$ if $n$ is even, and $n ~\&~ 1 = 1$ if $n$ is odd.
130+ More generally, $n$ is divisible by $2^{k}$ exactly when $n ~\&~ ( 2^{k} − 1) = 0$ .
131131
132132``` cpp
133- bool isDivisibleByPowerOf2(int x , int k) {
133+ bool isDivisibleByPowerOf2(int n , int k) {
134134 int powerOf2 = 1 << k;
135- return (x & (powerOf2 - 1)) == 0;
135+ return (n & (powerOf2 - 1)) == 0;
136136}
137137```
138- we can calculate $2^{k}$ by left shifting 1 by k positions. If function return true, x is divisible by $2^{k}$ otherwise not.
138+
139+ We can calculate $2^{k}$ by left shifting 1 by $k$ positions.
140+ The trick works, because $2^k - 1$ is a number that consists of exactly $k$ ones.
141+ And a number that is divisible by $2^k$ must have zero digits in those places.
139142
140143### Check if an integer is a power of 2
141144
0 commit comments