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;
}
}
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;
}
}
相关文章推荐
- LeetCode[342] Power of Four
- Leetcode_342_Power of Four
- Leetcode Power of Four 342
- LeetCode之342,Power of Four
- LeetCode 342 Power of Four
- Leetcode_342_Power of Four
- LeetCode 342 Power of Four
- Power of Four leetcode 342
- Leetcode 342 Power of Four
- LeetCode 第 342 题(Power of Four)
- leetcode 342 Power of Four C++
- LeetCode191 Number of 1 Bits. LeetCode231 Power of Two. LeetCode342 Power of Four
- leetcode 342 Power of four
- LeetCode 第 342 题(Power of Four)
- LeetCode 第 342 题(Power of Four)
- leetcode:bits:Power of Four(342)
- Python [Leetcode 342]Power of Four
- 【LeetCode-342】 Power of Four(C++)
- leetcode_342 Power of Four
- leetcode——342——Power of Four