mirror of
https://github.com/yangshun/tech-interview-handbook.git
synced 2026-02-12 15:16:23 +08:00
* 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>
1.2 KiB
1.2 KiB
id, title
| id | title |
|---|---|
| binary | Binary |
Study links
Notes
Questions involving binary representations and bitwise operations are asked sometimes and you must be absolutely familiar with how to convert a number from decimal form into binary form (and vice versa) in your chosen programming language.
Some helpful utility snippets:
- Test kth bit is set:
num & (1 << k) != 0. - Set kth bit:
num |= (1 << k). - Turn off kth bit:
num &= ~(1 << k). - Toggle the kth bit:
num ^= (1 << k). - To check if a number is a power of 2,
(num & num - 1) == 0or(num & (-num)) == num.
Corner cases
- Be aware and check for overflow/underflow
- Negative numbers