Sponsored
Sponsored
This approach utilizes dynamic programming to count the number of non-negative integers without consecutive ones. By breaking down the problem, we can avoid redundant work by storing solutions to subproblems.
Time Complexity: O(1) since we iterate over a fixed number of bits (30 bits for int).
Space Complexity: O(1) for storing a constant size dp array.
1class Solution:
2 def findIntegers(self, num: int) -> int:
3 dp = [0] * 31
4 dp[0] = 1
5 dp[1] = 2
6 for i in range(2, 31):
7 dp[i] = dp[i - 1] + dp[i - 2]
8
9 prev_bit = 0
10 result = 0
11
12 for i in range(29, -1, -1):
13 if (num & (1 << i)) != 0:
14 result += dp[i]
15 if prev_bit == 1:
16 return result
17 prev_bit = 1
18 else:
19 prev_bit = 0
20
21 return result + 1
22
23if __name__ == "__main__":
24 sol = Solution()
25 n = 5
26 print(sol.findIntegers(n))In Python, the solution similarly utilizes a dp list to manage the counts of valid integer representations without consecutive ones for binary integers up to 31-bit. This implementation iterates over each bit of num to calcualte the total valid integers.
In this approach, we tackle the problem recursively and use memoization to store and retrieve solutions to subproblems, thereby optimizing overlapping subproblem calculations.
Time Complexity: Generally O(log n), as the recursion iterates over each bit once.
Space Complexity: O(log n) due to the recursive call stack and memo storage.
1class Solution:
2 def __init__(self)
The Python solution mirrors the C++ solution by breaking down the integer into binary bits and evaluating recursively through depth-first search. It stores computed results in a dictionary to avoid re-calculating overlapping subproblems.