You are given a positive whole number num. Write it in binary with no leading zeros, then flip every bit: each 0 becomes 1 and each 1 becomes 0.
Return the number that the flipped bits spell. Only the bits from the leading 1 down are flipped; the zeros in front of it do not count.
Example 1
Input: num = 10 Output: 5 Why: 10 is 1010; flipped it is 0101, which is 5
2 more examples and the constraints
Example 2
Input: num = 6 Output: 1 Why: 6 is 110; flipped it is 001, which is 1
Example 3
Input: num = 7 Output: 0 Why: 7 is 111, so every bit flips to 0
Constraints
- 1 ≤ num ≤ 2,147,483,647 (2³¹ − 1)
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Flip bit by bitO(log num)
- All-ones mask + XORO(log num)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for num near 2³¹ | Verdict |
|---|---|---|---|
| Flip bit by bit | O(log num) | Passes; easy to follow | |
| All-ones mask + XOR | O(log num) | Best; one XOR at the end |
log num = the number of bits in num, at most 31.
Edge cases to test
- num = 1. 1 flips to 0. The answer can be 0 even though num is positive.
- All ones. 7 or 2,147,483,647: every bit flips to 0, so the answer is 0.
- A power of two. 1024 is 1 followed by ten 0s; the answer is ten 1s, 1023.
- The largest input. With a mask built as 2·mask + 1, it stops at 2³¹ − 1 and never overflows a 32-bit int.
Common mistakes
- Using
~num, which also flips the 32 − k leading zeros and gives a negative number. - Building the mask as
1 << (k + 1)without care, which can overflow when num has 31 bits. - Looping a fixed 32 times and flipping zeros above the leading 1.
How to talk through it
- 1Clarify. Only the bits from the leading 1 down are flipped, right? num is always at least 1?
- 2Give the simple loop. Read each bit with
& 1and a shift; where num has a 0, set that bit in the result. - 3Name the trick. XOR with 1 flips a bit, so XOR with a run of 1s as long as num flips them all.
- 4Build the mask safely. Grow it with
(mask << 1) | 1until it reaches num; it never goes past 2³¹ − 1. - 5Test out loud. Run 1, 7 and 1024, then the largest input, 2,147,483,647.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?