Skip to content

Commit 768e506

Browse files
Added largest_pow_of_two_le_num
1 parent e798e5a commit 768e506

File tree

2 files changed

+61
-0
lines changed

2 files changed

+61
-0
lines changed

DIRECTORY.md

+1
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,7 @@
5151
* [Index Of Rightmost Set Bit](bit_manipulation/index_of_rightmost_set_bit.py)
5252
* [Is Even](bit_manipulation/is_even.py)
5353
* [Is Power Of Two](bit_manipulation/is_power_of_two.py)
54+
* [Is Power Of Two](bit_manipulation/largest_pow_of_two_less_than_or_equal_to_a_number.py)
5455
* [Missing Number](bit_manipulation/missing_number.py)
5556
* [Numbers Different Signs](bit_manipulation/numbers_different_signs.py)
5657
* [Reverse Bits](bit_manipulation/reverse_bits.py)
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
"""
2+
Author : Naman Sharma
3+
Date : October 2, 2023
4+
5+
Task:
6+
Find largest power of 2 less than or equal to a given number
7+
8+
Implementation notes: Use bit manipulation.
9+
We start from 1 & left shift the set bit to check if (res<<1)<=number.
10+
Each left bit shift represents a pow of 2.
11+
12+
For example:
13+
number: 15
14+
res: 1 0b1
15+
2 0b10
16+
4 0b100
17+
8 0b1000
18+
16 0b10000 (Exit)
19+
"""
20+
21+
22+
def largest_pow_of_two_less_than_or_equal_to_a_number(number: int) -> int:
23+
"""
24+
Return the largest power of two less than or equal to a number.
25+
26+
>>> largest_pow_of_two_less_than_or_equal_to_a_number(0)
27+
0
28+
>>> largest_pow_of_two_less_than_or_equal_to_a_number(1)
29+
1
30+
>>> largest_pow_of_two_less_than_or_equal_to_a_number(-1)
31+
0
32+
>>> largest_pow_of_two_less_than_or_equal_to_a_number(3)
33+
2
34+
>>> largest_pow_of_two_less_than_or_equal_to_a_number(15)
35+
8
36+
>>> largest_pow_of_two_less_than_or_equal_to_a_number(99)
37+
64
38+
>>> largest_pow_of_two_less_than_or_equal_to_a_number(178)
39+
128
40+
>>> largest_pow_of_two_less_than_or_equal_to_a_number(999999)
41+
524288
42+
>>> largest_pow_of_two_less_than_or_equal_to_a_number(99.9)
43+
Traceback (most recent call last):
44+
...
45+
TypeError: Input value must be a 'int' type
46+
"""
47+
if isinstance(number, float):
48+
raise TypeError("Input value must be a 'int' type")
49+
if number <= 0:
50+
return 0
51+
res = 1
52+
while (res << 1) <= number:
53+
res <<= 1
54+
return res
55+
56+
57+
if __name__ == "__main__":
58+
import doctest
59+
60+
doctest.testmod()

0 commit comments

Comments
 (0)