Skip to content

Commit a86f247

Browse files
committed
EPI: closest int, same weight (py)
1 parent 9d4a582 commit a86f247

File tree

2 files changed

+13
-3
lines changed

2 files changed

+13
-3
lines changed

elements-of-programming-interviews/problem_mapping.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -66,7 +66,7 @@ problem_mapping = {
6666
"total": 10000
6767
},
6868
"Python: closest_int_same_weight.py": {
69-
"passed": 0,
69+
"passed": 10000,
7070
"total": 10000
7171
}
7272
},

elements-of-programming-interviews/python/closest_int_same_weight.py

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,18 @@
22

33

44
def closest_int_same_bit_count(x: int) -> int:
5-
# TODO - you fill in here.
6-
return 0
5+
original = x
6+
i = 0
7+
curr = prev = x & 1 != 0
8+
9+
while (prev == curr):
10+
x >>= 1
11+
prev = curr
12+
curr = x & 1 != 0
13+
i += 1
14+
15+
mask = (1 << i) | (1 << i-1)
16+
return original ^ mask
717

818

919
if __name__ == '__main__':

0 commit comments

Comments
 (0)