Leetcode 231: Power of Two

https://leetcode.com/problems/power-of-two/

Power of Two

Total Accepted: 32889 Total Submissions: 103319 Difficulty: Easy

Given an integer, write a function to determine if it is a power of two.

Code
class Solution(object):
    def isPowerOfTwo(self, n):
        """
        :type n: int
        :rtype: bool
        """
        return (n & (n-1)) == 0 and n > 0
        

 

Idea:

Using the idea that if a number is power of two, its binary format should be: `1000..`. Then the number subtracted one should be: `011111..`. So `(n&(n-1))==0` can be used to judge if a number if power of two. 

 

An follow up is to calculate number k to the power of n: power(n, k). You can see how to use divide and conquer to solve this problem in `O(logN)`: http://www.geeksforgeeks.org/write-a-c-program-to-calculate-powxn/https//nb4799.neu.edu/wordpress/?p=1078

 

Leave a comment

Your email address will not be published. Required fields are marked *