Non-negative Integers without Consecutive Ones - Problem
Given a positive integer n, you need to count how many integers in the range [0, n] have binary representations without consecutive ones.
In binary representation, consecutive ones mean two or more 1s appearing next to each other. For example:
5 (101₂)✅ Valid - no consecutive ones6 (110₂)❌ Invalid - has consecutive ones3 (11₂)❌ Invalid - has consecutive ones
Your task is to efficiently count all valid numbers from 0 to n inclusive that satisfy this constraint.
Challenge: Can you solve this without checking every single number individually?
Input & Output
example_1.py — Basic Case
$
Input:
n = 5
›
Output:
5
💡 Note:
The valid numbers are: 0 (0₂), 1 (1₂), 2 (10₂), 4 (100₂), 5 (101₂). Number 3 (11₂) and 6 (110₂) have consecutive ones, but 6 > 5 anyway.
example_2.py — Larger Number
$
Input:
n = 8
›
Output:
6
💡 Note:
Valid numbers: 0 (0₂), 1 (1₂), 2 (10₂), 4 (100₂), 5 (101₂), 8 (1000₂). Numbers 3, 6, 7 have consecutive 1s in binary.
example_3.py — Edge Case
$
Input:
n = 1
›
Output:
2
💡 Note:
Valid numbers are 0 (0₂) and 1 (1₂). Both have no consecutive ones since they're single bits.
Constraints
- 1 ≤ n ≤ 109
- n is a positive integer
- Binary representation constraint: No consecutive 1s allowed
Visualization
Tap to expand
Understanding the Visualization
1
Pattern Recognition
Valid strings of length n = Valid strings ending in 0 + Valid strings ending in 1
2
Recurrence Relation
If string ends in 0, previous bit can be 0 or 1. If ends in 1, previous must be 0
3
Fibonacci Connection
This gives us F(n) = F(n-1) + F(n-2), the Fibonacci recurrence
Key Takeaway
🎯 Key Insight: The problem combines Fibonacci sequence properties with digit DP technique to efficiently count valid numbers without checking each one individually.
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code