美文网首页Leetcode刷题笔记
第二十七天 Power of Two

第二十七天 Power of Two

作者: 业余马拉松选手 | 来源:发表于2018-09-16 00:12 被阅读0次

嗯,再来刷一道,继续腾讯秋招的50题吧

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

这道题也是有比较tricky的方法了

python提供一个数字转成字符串的方法,bin
那么如果是2的幂的话,那么就应该只有1个1,这样思路就比较简单了呢

class Solution:
    def isPowerOfTwo(self, n):
        """
        :type n: int
        :rtype: bool
        """
        if n < 0:
            return False
        strNum = bin(n)
        if strNum.count("1") == 1:
            return True
        else:
            return False

相关文章

网友评论

    本文标题:第二十七天 Power of Two

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