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) 判断。由于4n=(3+1)n,因式分解可知,(3+1)n 可分为3的次方项,3+1的前后两项乘积项,和1的n次方,即1。故4n1是3的倍数。
代码如下:

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
原创粉丝点击