Problem 600 · LeetCode 600(opens in a new tab)
Non-negative Integers without Consecutive Ones
HardBit manipulation
You are given a positive integer n. Count the whole numbers from 0 to n, both included, whose binary form never has two 1 bits side by side.
For instance, 5 is 101 and counts, but 6 is 110 and does not.
Example 1
Input: n = 10 Output: 8 Why: 0, 1, 10, 100, 101, 1000, 1001 and 1010 in binary
2 more examples and the constraints
Example 2
Input: n = 7 Output: 5 Why: 0, 1, 2, 4 and 5; 3, 6 and 7 all contain 11
Example 3
Input: n = 3 Output: 3 Why: 0, 1 and 2; 3 is 11
Constraints
- 1 ≤ n ≤ 1,000,000,000
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Grow only valid numbersO(answer)
- Fibonacci over the bitsO(log n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for n = 1,000,000,000 | Verdict |
|---|---|---|---|
| Grow only valid numbers | O(answer) | Passes; one call per answer | |
| Fibonacci over the bits | O(log n) | Best; about 60 steps |
n is the upper limit; log n is its number of bits, at most 30. Checking every number one by one would be another 500 times slower.
Edge cases to test
- n = 1. 0 and 1 are both valid: the answer is 2.
- n itself contains 11. n = 7 (111) stops at the second 1 and must not add 1 for n.
- n is a power of two. n = 8 (1000) adds f[3] = 5, then 1 for n itself: 6.
- n has alternating bits. n = 10 (1010) adds at every 1 and then counts n itself.
- The largest n. 1,000,000,000 has 30 bits, so f must reach at least f[29]; the answer, 2,178,309, fits easily.
Common mistakes
- Adding 1 for n even when n contains 11.
- Starting f at f[1] = 1 instead of 2, which forgets that a 1-bit string can be 0 or 1.
- Counting from 1 instead of 0, so the answer is one too small.
How to talk through it
- 1Clarify. Does 0 count? Is n itself included? How large can n be?
- 2Give the brute force. Check x & (x >> 1) for every x: O(n), a billion steps at the limit.
- 3Count strings, not numbers. Valid strings of length i satisfy f[i] = f[i − 1] + f[i − 2]: Fibonacci.
- 4Walk n's bits. At each 1, add f[i] for putting a 0 there; stop at the first 11; add 1 for n at the end.
- 5Test out loud. Run n = 7, which contains 11, and n = 10, which does not, before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?