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

Python [Leetcode 342]Power of Four

时间:2016-07-30 22:22:37      阅读:162      评论:0      收藏:0      [点我收藏+]

标签:

题目描述:

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.

解题思路:

位操作。

首先判断是不是只有一位数字为1,其余为0

然后判断为1的位置是不是奇数位

代码如下:

class Solution(object):
    def isPowerOfFour(self, num):
        """
        :type num: int
        :rtype: bool
        """
        if num & (num - 1) != 0:
        	return False
        if num & 0x55555555 == 0:
        	return False

        return True

  

 

Python [Leetcode 342]Power of Four

标签:

原文地址:http://www.cnblogs.com/zihaowang/p/5721715.html

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