Skip to content

Commit 14dee00

Browse files
Update next_higher_same_ones.py
1 parent 5b93e2b commit 14dee00

File tree

1 file changed

+12
-13
lines changed

1 file changed

+12
-13
lines changed

bit_manipulation/next_higher_same_ones.py

Lines changed: 12 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -24,33 +24,32 @@
2424
>>> next_higher_same_ones(-5) # negative not allowed
2525
Traceback (most recent call last):
2626
...
27-
ValueError: n must be a non-negative integer
27+
ValueError: input_value must be a non-negative integer
2828
"""
29-
3029
from __future__ import annotations
3130

3231

33-
def next_higher_same_ones(n: int) -> int:
34-
"""Return the next higher integer with the same number of set bits as n.
32+
def next_higher_same_ones(input_value: int) -> int:
33+
"""Return the next higher integer with the same number of set bits as the input.
3534
36-
:param n: Non-negative integer
35+
:param input_value: Non-negative integer
3736
:return: Next higher integer with same popcount or -1 if none
38-
:raises ValueError: if n < 0
37+
:raises ValueError: if input_value < 0
3938
"""
40-
if n < 0:
41-
raise ValueError("n must be a non-negative integer")
42-
if n == 0:
39+
if input_value < 0:
40+
raise ValueError("input_value must be a non-negative integer")
41+
if input_value == 0:
4342
return -1
4443

4544
# snoob algorithm
4645
# c = rightmost set bit
47-
c = n & -n
48-
# r = ripple carry: add c to n
49-
r = n + c
46+
c = input_value & -input_value
47+
# r = ripple carry: add c to input_value
48+
r = input_value + c
5049
if r == 0:
5150
return -1
5251
# ones = pattern of ones that moved from lower part
53-
ones = ((r ^ n) >> 2) // c
52+
ones = ((r ^ input_value) >> 2) // c
5453
return r | ones
5554

5655

0 commit comments

Comments
 (0)