Is Power of Two
by Isai Damier, Android Engineer @ Google
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | #====================================================================== # Author: Isai Damier # Title: Is Power of Two # Project: geekviewpoint # Package: algorithms # # Statement: # Indicate whether the given integer n is a power of two. # # Sample Input: 16 # Sample Output: true # # Technical Details: # A number that is a power of two only has one set bit: 0 = 0; 2 = 10; # 4 = 100; 8 = 1000; 16 = 10000; etc. Therefore checking whether a # number is a power of two is as simple as clearing the lowest set bit # and then checking that the result is equal to zero. #====================================================================== def isPowerOfTwo( n ): return 0 = = ( n & ( n - 1 ) ) |
1 2 3 4 5 6 7 8 | import unittest from algorithms import bitwise as bits class Test( unittest.TestCase ): def testIsPowerOfTwo( self ): for i in range ( 1 , 31 ) : self .assertTrue( bits.isPowerOfTwo( 2 * * i ) ) |