您的位置:首页 > 其它

LeetCode 342 Power of Four (位运算)

2016-09-01 17:27 337 查看
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?

Credits:

Special thanks to
@yukuairoy for adding this problem and creating all test cases.

题目链接:https://leetcode.com/problems/power-of-four/

题目分析:O(1)判断是不是4的幂,一行代码不能更多了吧,首先必须是个整数,其次二进制中必须只有一个1且1的位置必须是(0x55555555)当中的某个

public class Solution {
public boolean isPowerOfFour(int num) {
return num > 0 && (num & (num - 1)) == 0 && ((num - 1) % 3) == 0;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: