Reputation:
Looking for something along the lines of:
t = 1
get_floor_bin(t)
#1
t = 2
get_floor_bin(t)
#2
t = 3
get_floor_bin(t)
#2
t = 7
get_floor_bin(t)
#4
t = 15
get_floor_bin(t)
#8
t = 16
get_floor_bin(t)
#16
My current approach involves creating a list of binary numbers, and searching for each individual closest floor number within the list, but I was wondering if there are more clever approaches.
Thanks!
Upvotes: 3
Views: 230
Reputation: 37013
Is this what you need? Your explanation isn't terribly easy to understand.
for i in 1, 2, 3, 7, 15, 16:
print 1 << (i.bit_length() - 1)
This gives:
1
2
2
4
8
16
Upvotes: 18
Reputation: 19601
The expression 1 << int(math.floor(math.log(x,2)))
will give you the correct result:
import math
for x in (1,2,3,7,15,16):
print x, 1 << int(math.floor(math.log(x,2)))
1 1
2 2
3 2
7 4
15 8
16 16
Upvotes: 2
Reputation: 34017
Not sure if this way is fast enough:
In [394]: def largestPower(n):
...: return int('1'+'0'*(len(bin(n))-3), 2)
In [395]: largestPower(15)
Out[395]: 8
In [396]: largestPower(1)
Out[396]: 1
In [397]: largestPower(7)
Out[397]: 4
Upvotes: 0