位运算 —— 2的幂,3的幂,4的幂

2的幂、4的幂

题目:Given an integer, write a function to determine if it is a power of two.
2的幂——即数字按位展开只有一位为1,所以 num&(num - 1) ==0;

public class Solution {
    public boolean isPowerOfTwo(int n) {
        return (n>0)&&((n&(n-1))==0);  
    }
}

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?

4的幂——相较于2的幂而言对二进制位要求更高,不仅要求数字按位展开只有一位为1,且1的后面必须有偶数个0,即…00000100,…00010000,…01000000。

法一:
(num-1)后必然是三的倍数:

public class Solution {
    public boolean isPowerOfFour(int num) {
      return ((num & (num - 1)) == 0) && ((num - 1) % 3 == 0);
    }
}

法二,既然已规定32位,那么只有将所有的4的幂的位置上置1——即0x…101010101010101(0x55555555)与num相与为num本身即可;

public class Solution {
    public boolean isPowerOfFour(int num) {
    return (num >0)&&((num & (num - 1)) == 0) && ((num & 0x55555555) == num);
    }
}

法三:由幂的定义出发:利用换低公式 x = log4(num )(以4为底),x为整数即可。

Given an integer, write a function to determine if it is a power of three.

public class Solution {
    public boolean isPowerOfFour(int num) {
    return (num > 0) && (Math.ceil(Math.log10(num) / Math.log10(4)) - Math.log10(num) / Math.log10(4) == 0);
    } 
}

Follow up:
Could you do it without using any loop / recursion?
3的幂——由幂的定义出发:利用换低公式x = log3(num )(以3为底),x为整数即可;或者Math.pow(log3(num)) == num即可

public class Solution {
    public boolean isPowerOfThree(int n) {

   return (n > 0) &&(Math.pow(3,Math.round((Math.log(n)/Math.log(3))))==n);

    }
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值