Skip to content

Commit d63be7c

Browse files
authored
Create non-negative-integers-without-consecutive-ones.py
1 parent 1bad2c3 commit d63be7c

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed
+41
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
# Time: O(1)
2+
# Space: O(1)
3+
4+
# Given a positive integer n, find the number of non-negative integers less than
5+
# or equal to n, whose binary representations do NOT contain consecutive ones.
6+
#
7+
# Example 1:
8+
# Input: 5
9+
# Output: 5
10+
# Explanation:
11+
# Here are the non-negative integers <= 5 with their corresponding binary representations:
12+
# 0 : 0
13+
# 1 : 1
14+
# 2 : 10
15+
# 3 : 11
16+
# 4 : 100
17+
# 5 : 101
18+
# Among them, only integer 3 disobeys the rule (two consecutive ones) and the other 5 satisfy the rule.
19+
# Note: 1 <= n <= 10^9
20+
21+
class Solution(object):
22+
def findIntegers(self, num):
23+
"""
24+
:type num: int
25+
:rtype: int
26+
"""
27+
dp = [0] * 32
28+
dp[0], dp[1] = 1, 2
29+
for i in xrange(2, len(dp)):
30+
dp[i] = dp[i-1] + dp[i-2]
31+
result, prev_bit = 0, 0
32+
for i in reversed(xrange(31)):
33+
if (num & (1 << i)) != 0:
34+
result += dp[i]
35+
if prev_bit == 1:
36+
result -= 1
37+
break
38+
prev_bit = 1
39+
else:
40+
prev_bit = 0
41+
return result + 1

0 commit comments

Comments
 (0)