342. Power of Four
来源:互联网 发布:js confirm 重写 编辑:程序博客网 时间:2024/05/18 11:49
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?
Integer API 解法
4的次方的二进制码只有一个1,且1的位置为奇数位,即后面的零为偶数个。则代码如下:
public class Solution { public boolean isPowerOfFour(int num) { return Integer.numberOfTrailingZeros(num) % 2 == 0 && Integer.bitCount(num) == 1 && num > 0; }}
String 解法
得到 num 的二进制字符串,若 num 是4的倍数,则字符串应该为1开头,偶数个0结束。通过比较来判断,代码如下:
public class Solution { public boolean isPowerOfFour(int num) { String s = Integer.toBinaryString(num); int len = s.length(); if(len % 2 != 1) return false; String temp = "1"; for(int i = 0; i < len - 1; i++) { temp += "0"; } return s.equals(temp); }}
正则解法
同理,构建匹配式来比较是否是4的倍数,运算速度相当低,看看就好。代码如下:
import java.util.regex.Matcher;import java.util.regex.Pattern;public class Solution { public boolean isPowerOfFour(int num) { String s = Integer.toBinaryString(num); Pattern pattern = Pattern.compile("^1(00)*$"); Matcher m = pattern.matcher(s); return m.find(); }}
数学解法
首先 num 必然是2的倍数,则可由 n & (n-1) 判断。由于
代码如下:
public class Solution { public boolean isPowerOfFour(int num) { return num > 0 && (num&(num - 1)) == 0 && (num - 1) % 3 == 0; }}
位运算
由于二进制时1必然出现在奇数位,则可与上0x55555555来判断。运算效率最高,代码如下:
public class Solution { public boolean isPowerOfFour(int num) { return num > 0 && (num&(num - 1)) == 0 && (num & 0x55555555) = 0; }}
0 0
- 342. Power of Four
- 342. Power of Four
- 342. Power of Four
- 342. Power of Four
- 342. Power of Four
- 342. Power of Four
- 342. Power of Four
- 342. Power of Four
- 342. Power of Four
- 342. Power of Four
- 342. Power of Four
- 342. Power of Four
- 342. Power of Four
- 342. Power of Four
- 342. Power of Four
- 342. Power of Four*
- 342. Power of Four
- 342. Power of Four
- VB6 Advanced Filter Function(2)
- Remote Desktop
- 121.After performing a clean shut down of the database instance for maintenance, you mount the datab
- RecyclerView 复用出现 CheckBox 或者 设置背景混乱问题
- interpolator插值器图形生成器,After Effects速率表示转换器
- 342. Power of Four
- hdu 1870 愚人节的礼物
- jQuery length和size()区别总结如下:
- 史上最好的BP算法图解
- cocos2dx 中 CC_DLL解析
- mysql 下 计算 两点 经纬度 之间的距离
- linux qcom LCD framwork
- HttpClient
- mysql读写分离的完整配置