forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcount-binary-palindromic-numbers.py
More file actions
40 lines (35 loc) · 944 Bytes
/
Copy pathcount-binary-palindromic-numbers.py
File metadata and controls
40 lines (35 loc) · 944 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# Time: O(logn)
# Space: O(1)
# bitmasks, combinatorics
class Solution(object):
def countBinaryPalindromes(self, n):
"""
:type n: int
:rtype: int
"""
def length(n):
result = 0
while n:
result += 1
n >>= 1
return result
def reverse(n, l):
result = 0
for i in xrange(l):
if n&(1<<i):
result |= 1<<((l-1)-i)
return result
l = length(n)//2
return ((1<<l)-1)+(n>>l)+int(((n>>l)<<l)|reverse(n>>(length(n)-l), l) <= n)
# Time: O(logn)
# Space: O(logn)
# bitmasks, combinatorics
class Solution2(object):
def countBinaryPalindromes(self, n):
"""
:type n: int
:rtype: int
"""
s = map(int, bin(n)[2:])
l = len(s)//2
return ((1<<l)-1)+(n>>l)+int(s[:len(s)-l]+s[:l][::-1] <= s)