leetcode 231. Power of Two(python)

215 阅读1分钟

描述

Given an integer n, return true if it is a power of two. Otherwise, return false.

An integer n is a power of two, if there exists an integer x such that n == 2^x.

Example 1:

Input: n = 1
Output: true
Explanation: 2^0 = 1	

Example 2:

Input: n = 16 Output: true Explanation: 2^4 = 16

Example 3:

Input: n = 3
Output: false

Example 4:

Input: n = 4
Output: true

Example 5:

Input: n = 5
Output: false

Note:

-2^31 <= n <= 2^31 - 1

解析

根据题意,就是判断 n 是不是 2 的 x 次方的值,用递归的方法进行判断。如果 n 小于等于 0 ,直接返回 False ,如果 n 为 1 ,直接返回 True ,如果 n%2==0 那么递归对 n//2 进行上述类似的操作。其他情况直接返回 False 。

解答

class Solution(object):
    def isPowerOfTwo(self, n):
        """
        :type n: int
        :rtype: bool
        """
        if n<=0:
            return False
        elif n == 1:
            return True
        elif n % 2 == 0 :
            return self.isPowerOfTwo(n//2)
        else:
            return False
        	      
		

运行结果

Runtime: 16 ms, faster than 83.61% of Python online submissions for Power of Two.
Memory Usage: 13.5 MB, less than 34.60% of Python online submissions for Power of Two.

解析

不用递归,直接写逻辑代码。

解答

class Solution(object):
    def isPowerOfTwo(self, n):
        """
        :type n: int
        :rtype: bool
        """
        if n<=0:
            return False
        if n==1:
            return True
        while n%2==0:
            n//=2
        return n==1


		

运行结果

Runtime: 16 ms, faster than 83.61% of Python online submissions for Power of Two.
Memory Usage: 13.5 MB, less than 34.60% of Python online submissions for Power of Two.

原题链接:leetcode.com/problems/po…

您的支持是我最大的动力