美文网首页
LeetCode 231. Power of Two 2的幂

LeetCode 231. Power of Two 2的幂

作者: singed | 来源:发表于2018-08-27 14:07 被阅读0次

链接

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

要求

给定一个整数,编写一个函数来判断它是否是 2 的幂次方。

输入: 1
输出: true
解释: 20 = 1

输入: 16
输出: true
解释: 24 = 16

输入: 218
输出: false

相关代码

思路:
被2整除直至余数为1,则返回True。不能整除则返回False

class Solution(object):
    def isPowerOfTwo(self, n):
        while n > 1:
            if n % 2:
                return False
            else:
                n /= 2
        else:
            if n == 1:
                return True
            else:
                return False

相关文章

网友评论

      本文标题:LeetCode 231. Power of Two 2的幂

      本文链接:https://www.haomeiwen.com/subject/hmnziftx.html