@@ -45,7 +45,7 @@ All those introduced operators are instant (same speed as an addition) on a CPU
45
45
46
46
### Bitwise operators
47
47
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.
49
49
If both bits are 1, the corresponding result bit is set to 1. Otherwise, the corresponding result bit is set to 0.
50
50
51
51
- $|$ : 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) {
126
126
127
127
### Check if the number is divisible by a power of 2
128
128
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$ .
131
131
132
132
``` cpp
133
- bool isDivisibleByPowerOf2 (int x , int k) {
133
+ bool isDivisibleByPowerOf2 (int n , int k) {
134
134
int powerOf2 = 1 << k;
135
- return (x & (powerOf2 - 1)) == 0;
135
+ return (n & (powerOf2 - 1)) == 0;
136
136
}
137
137
```
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.
139
142
140
143
### Check if an integer is a power of 2
141
144
0 commit comments