Quantcast
Channel: 书影 - Entries for the tag leetcode
Viewing all articles
Browse latest Browse all 559

[LeetCode]Power of Four

$
0
0

题目描述:

LeetCode 342. Power of Four

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?

题目大意:

给定一个整数(32位有符号),编写函数判断它是否是4的幂。

测试用例如题目描述。

进一步思考:你可以不用循环/递归解决问题吗?

解题思路:

若一个整数是4的幂,则其二进制形式具有如下特点:

1. 最高位为1,其余位为0

2. 0的个数为偶数

条件1可以用num & (num - 1) == 0判断

条件2可以用num & 0x55555555 > 0判断

Python代码:

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

 


Viewing all articles
Browse latest Browse all 559

Trending Articles