[LeetCode]231. Power of Two&326. Power of Three&342. Power of Four

来源:互联网 发布:iphone硬件检测软件 编辑:程序博客网 时间:2024/06/08 02:15

231 . Power of Two
Easy

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

2ms:

public boolean isPowerOfTwo(int n) {        if(n==0) return false;        while(n%2==0){            n /= 2;        }        return n==1;    }

2ms:

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

326 . Power of Three
Easy

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?

23ms:

  public boolean isPowerOfThree(int n) {        return ( n>0 &&  1162261467%n==0);    }

31ms:

 public boolean isPowerOfThree(int n) {        if(n==0)             return false;         while(n%3==0)             n /= 3;         return n==1;    }

342 . Power of Four
Easy

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?

2ms:

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

2ms:

 public boolean isPowerOfFour(int num) {        int n=0;          while(num>0){              int tmp = num&3;              if(tmp==3||tmp==2)                  return false;              n+=tmp;              num=num>>2;          }          return n==1;    }
0 0
原创粉丝点击