Skip to content

Instantly share code, notes, and snippets.

@peroon
Last active October 9, 2018 21:46
Show Gist options
  • Save peroon/1bf8b9dfa2ef6bf7edd5bd53e216b2eb to your computer and use it in GitHub Desktop.
Save peroon/1bf8b9dfa2ef6bf7edd5bd53e216b2eb to your computer and use it in GitHub Desktop.
def near_power_of_two(v):
if v < 0:
return 0
if v == 0:
return 0
v -= 1
count = 0
while v != 0:
v = v >> 1
count += 1
return 2**count
print(near_power_of_two(0))
print(near_power_of_two(1))
print(near_power_of_two(2))
print(near_power_of_two(3))
print(near_power_of_two(4))
print(near_power_of_two(31))
print(near_power_of_two(32))
print(near_power_of_two(33))
"""output
0
1
2
4
4
32
32
64
"""
@peroon
Copy link
Author

peroon commented Oct 9, 2018

2の冪

1, 2, 4, 8, 16, 32, 64, 128, 256, 512,・・・

2**16

65536

2**32

4294967296

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment