-
Notifications
You must be signed in to change notification settings - Fork 48
/
Copy path080-get_next.py
53 lines (51 loc) · 1.85 KB
/
080-get_next.py
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
41
42
43
44
45
46
47
48
49
50
51
52
53
class Bits(object):
def get_next_largest(self, num):
if num is None:
raise TypeError('num cannot be None')
if num <= 0:
raise ValueError('num cannot be 0 or negative')
num_ones = 0
num_zeroes = 0
num_copy = num
# We'll look for index, which is the right-most non-trailing zero
# Count number of zeroes to the right of index
while num_copy != 0 and num_copy & 1 == 0:
num_zeroes += 1
num_copy >>= 1
# Count number of ones to the right of index
while num_copy != 0 and num_copy & 1 == 1:
num_ones += 1
num_copy >>= 1
# Determine index and set the bit
index = num_zeroes + num_ones
num |= 1 << index
# Clear all bits to the right of index
num &= ~((1 << index) - 1)
# Set bits starting from 0
num |= ((1 << num_ones - 1) - 1)
return num
def get_next_smallest(self, num):
if num is None:
raise TypeError('num cannot be None')
if num <= 0:
raise ValueError('num cannot be 0 or negative')
num_ones = 0
num_zeroes = 0
num_copy = num
# We'll look for index, which is the right-most non-trailing one
# Count number of zeroes to the right of index
while num_copy != 0 and num_copy & 1 == 1:
num_ones += 1
num_copy >>= 1
# Count number of zeroes to the right of index
while num_copy != 0 and num_copy & 1 == 0:
num_zeroes += 1
num_copy >>= 1
# Determine index and clear the bit
index = num_zeroes + num_ones
num &= ~(1 << index)
# Clear all bits to the right of index
num &= ~((1 << index) - 1)
# Set bits starting from 0
num |= (1 << num_ones + 1) - 1
return num