![]() |
VOOZH | about |
Given two positive integers n and m, check whether n is divisible by 2^m without using arithmetic operators
Examples:
Input: n = 8, m = 2
Output: Yes
Explanation: 2^2=4, and 8 is divisible by 4.Input: n = 14, m = 3
Output: No
Explanation: 2^3=8, and 14 is not divisible by 8.
The idea of this approach is based on the bitwise properties of powers of 2. A number is divisible by 2 if its least significant bit (LSB) is 0, divisible by 4 if the two least significant bits are 0, divisible by 8 if the three least significant bits are 0, and so on. Using this property, a number n is divisible by 2^m if its last m bits are all 0.
We can check this using the expression: n & ((1 << m) - 1)
Here’s how it works:
Yes