Check if a number is a power of 2

This representation may be easier to understand for some people.
If a number is power of two then `AND` operation between the number and its complement will result into the same number.
pull/196/head
Saddam H 5 years ago committed by GitHub
parent a5abb22e66
commit b00fd2b526
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -17,7 +17,7 @@ Some helpful utility snippets:
- Set k<sup>th</sup> bit: `num |= (1 << k)`.
- Turn off k<sup>th</sup> bit: `num &= ~(1 << k)`.
- Toggle the k<sup>th</sup> bit: `num ^= (1 << k)`.
- To check if a number is a power of 2, `num & num - 1 == 0`.
- To check if a number is a power of 2, `num & num - 1 == 0` or `num & (-num) == num`.
## Corner cases

Loading…
Cancel
Save