Input: n =5Output: 5Explanation:
Here are the non-negative integers <=5with their corresponding binary representations:0:01:12:103:114:1005:101Among them, only integer 3 disobeys the rule(two consecutive ones) and the other 5 satisfy the rule.
We count numbers without consecutive ones by building them bit by bit, using DP to avoid recomputation. For each bit, we decide to place 0 or 1, but only place 1 if the previous bit is 0. We also ensure we do not exceed n by tracking tight bounds.
Precompute fib[i] where fib[i] is the number of valid binary numbers of length i (no consecutive ones). This follows Fibonacci because for each bit, we can place 0 (any previous) or 1 (only if previous is 0).
Traverse the bits of n from highest to lowest:
If current bit is 1, add fib[i] to ans (all numbers with 0 at this bit and any valid below).
If two consecutive 1s are found, break (no more valid numbers above).
Add 1 for n itself if it does not contain consecutive ones.
classSolution {
public:int findIntegers(int n) {
int fib[32] = {1, 2};
for (int i =2; i <32; ++i) fib[i] = fib[i-1] + fib[i-2];
int ans =0, prev =0;
for (int i =30; i >=0; --i) {
if (n & (1<< i)) {
ans += fib[i];
if (prev) return ans;
prev =1;
} else prev =0;
}
return ans +1;
}
};
classSolution {
publicintfindIntegers(int n) {
int[] fib =newint[32];
fib[0]= 1; fib[1]= 2;
for (int i = 2; i < 32; ++i) fib[i]= fib[i-1]+ fib[i-2];
int ans = 0, prev = 0;
for (int i = 30; i >= 0; --i) {
if ((n & (1 << i)) != 0) {
ans += fib[i];
if (prev == 1) return ans;
prev = 1;
} else prev = 0;
}
return ans + 1;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
classSolution {
funfindIntegers(n: Int): Int {
val fib = IntArray(32)
fib[0] = 1; fib[1] = 2for (i in2 until 32) fib[i] = fib[i-1] + fib[i-2]
var ans = 0; var prev = 0for (i in30 downTo 0) {
if ((n shr i) and 1==1) {
ans += fib[i]
if (prev ==1) return ans
prev = 1 } else prev = 0 }
return ans + 1 }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
classSolution:
deffindIntegers(self, n: int) -> int:
fib = [1, 2] + [0] *30for i in range(2, 32):
fib[i] = fib[i-1] + fib[i-2]
ans =0 prev =0for i in range(30, -1, -1):
if n & (1<< i):
ans += fib[i]
if prev:
return ans
prev =1else:
prev =0return ans +1