mirror of
https://github.com/yangshun/tech-interview-handbook.git
synced 2025-07-28 12:43:12 +08:00
content: check if a number is a power of 2 (#196)
* 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. * Update binary.md Co-authored-by: Yangshun Tay <tay.yang.shun@gmail.com>
This commit is contained in:
@ -17,7 +17,7 @@ Some helpful utility snippets:
|
|||||||
- Set k<sup>th</sup> bit: `num |= (1 << k)`.
|
- Set k<sup>th</sup> bit: `num |= (1 << k)`.
|
||||||
- Turn off 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)`.
|
- 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
|
## Corner cases
|
||||||
|
|
||||||
|
Reference in New Issue
Block a user