美文网首页
231. Power of Two

231. Power of Two

作者: codingXue | 来源:发表于2016-05-11 11:35 被阅读6次

    问题描述

    Given an integer, write a function to determine if it is a power of two.
    Credits:Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.

    思路分析

    1. 用log函数,判断得到的指数是否约为整数。Runtime: 76 ms, which beats 5.28% of Python submissions.
    2. 循换进行模2判断并右移一位。Runtime: 68 ms, which beats 13.69% of Python submissions.
    3. 将十进制数转为二进制字符串,除第一位外其他位均为0则该数字是2的幂。Runtime: 56 ms, which beats 67.47% of Python submissions.

    AC代码

    class Solution(object):
        def isPowerOfTwo(self, n):
            if n <= 0:
                return False
            return n == 1 or not '1' in bin(n)[3:]
    

    相关文章

      网友评论

          本文标题:231. Power of Two

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