File tree 1 file changed +60
-0
lines changed
1 file changed +60
-0
lines changed Original file line number Diff line number Diff line change
1
+ """
2
+ Author : Naman Sharma
3
+ Date : October 2, 2023
4
+
5
+ Task:
6
+ To Find the 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_le_num (number : int ) -> int :
23
+ """
24
+ Return the largest power of two less than or equal to a number.
25
+
26
+ >>> largest_pow_of_two_le_num(0)
27
+ 0
28
+ >>> largest_pow_of_two_le_num(1)
29
+ 1
30
+ >>> largest_pow_of_two_le_num(-1)
31
+ 0
32
+ >>> largest_pow_of_two_le_num(3)
33
+ 2
34
+ >>> largest_pow_of_two_le_num(15)
35
+ 8
36
+ >>> largest_pow_of_two_le_num(99)
37
+ 64
38
+ >>> largest_pow_of_two_le_num(178)
39
+ 128
40
+ >>> largest_pow_of_two_le_num(999999)
41
+ 524288
42
+ >>> largest_pow_of_two_le_num(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 ()
You can’t perform that action at this time.
0 commit comments