[LeetCode] 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

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?

解题思路

如果一个数为4n,则它等于n个4相乘。乘以4可以化为左移2位的位运算,因此4n规律如下:

0000000000000001
0000000000000100
0000000000010000
0000000001000000
0000000100000000

二进制表示中仅有一个1,且1位于奇数位处。
可将此题与 Power of Two进行类比,主要区别在于判断等于1的位是否位于奇数位处。

实现代码

// Runtime: 2 ms
public class Solution {
    public boolean isPowerOfFour(int num) {
        return num > 0 && (num & (num - 1)) == 0 && (num & 0x55555555) != 0 ; 
    }
}
目录
相关文章
LeetCode 342. Power of Four
给定一个整数 (32 位有符号整数),请编写一个函数来判断它是否是 4 的幂次方。
76 0
LeetCode 342. Power of Four
|
Java C++
LeetCode之Power of Two
LeetCode之Power of Two
115 0
|
Java
[LeetCode]--326. Power of Three
Given an integer, write a function to determine if it is a power of three. Follow up: Could you do it without using any loop / recursion? Credits: Special thanks to @dietpepsi for addin
1111 0
[LeetCode]--231. Power of Two
Given an integer, write a function to determine if it is a power of two. Credits: Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases. 如果是power of
1088 0
LeetCode 326 Power of Three(3的幂)(递归、Log函数)
版权声明:转载请联系本人,感谢配合!本站地址:http://blog.csdn.net/nomasp https://blog.csdn.net/NoMasp/article/details/50540517 翻译 给定一个整型数,写一个函数决定它是否是3的幂(翻译可能不太合适…… 跟进: 你是否可以不用任何循环或递归来完成。
782 0
LeetCode 231 Power of Two(2的幂)
版权声明:转载请联系本人,感谢配合!本站地址:http://blog.csdn.net/nomasp https://blog.csdn.net/NoMasp/article/details/50541137 翻译 给定一个整型数,写一个函数来决定它是否是2的幂。
700 0