Power of Two & Power of Three & Power of Four

 Check Power of 2

Using O(1) time to check whether an integer n is a power of 2.

Example

For n=4, return true;

For n=5, return false;

奇数总是有超过2个1.

class Solution {
public boolean checkPowerOf2(int n) {
if(n <= ) return false;
return (n & (n - )) == ? true : false;
}
};

 Check Power of 3

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?

 public class Solution {
public boolean isPowerOfThree(int n) {
if (n == ) return false; if (n == ) return true; if (n > )
return n % == && isPowerOfThree(n / );
else
return false;
}
}

Check Power of 4

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.

 private boolean smartBit(long num){
return (num > ) && ((num & (num - )) == ) && ((num & 0x5555555555555555l) == num);
}

Explanation:

The magic numbers might seem very confusing. But they are not random (obviously!). Let us start with 0X55555555. Binary representation of 5 is 0101. So 0X55555555 has 16 ones, 16 zeros and the ones,zeros take alternate positions.

上一篇:centos 安装 ffmpeg


下一篇:(菜鸟要飞系列)四,基于Asp.Net MVC5的后台管理系统(zTree绑定Json数据生成树)