码迷,mamicode.com
首页 > 编程语言 > 详细

python1

时间:2016-04-18 22:17:31      阅读:139      评论:0      收藏:0      [点我收藏+]

标签:

leetcode上面的很简单的题目

 

 

Given an integer (signed 32 bits), write a function to check whether it is a power of 4.

Example:
Given num = 16, return true. Given num = 5, return false.

Follow up: Could you solve it without loops/recursion?

 

 

python解决方案:

class Solution(object):
    def isPowerOfFour(self, num):
    
    """
    :type num: int
    :rtype: bool
    """
    while num > 0 and num & 3 == 0:
        num >>= 2
    return num == 1

 

题解:  

如果是4的倍数,表示成二进制的话

  4  100

  16   10000

  64   1000000

  就是这种形式

 所以代码的思路就是

 整型的num

 每回判断它的后两位是不是0 (也即和3相与结果是不是0)

 然后num=num/4  (即右移两位)

  判断最后剩下的是不是一。

 

python1

标签:

原文地址:http://www.cnblogs.com/wangccc/p/5405748.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!