LeetCode 231. Power of Two

原题链接在这里:https://leetcode.com/problems/power-of-two/

题目:

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

题解:

bit manipulation, 若是2的幂数,二进制表示时只应该最高一位是1, 其他全是0.

只应该有一个1 bit. 可以用Integer.bitCount(n) == 1检查或者 n&(n-1)消除唯一的一个1 bit.

Time Complexity: O(1). Space: O(0).

AC Java:

1 public class Solution {
2     public boolean isPowerOfTwo(int n) {
3         if(n <= 0){
4             return false;
5         }
6         return (n&(n-1)) == 0;
7     }
8 }

一直除以2, 看能不能直到1.

Time Complexity: O(logn). Space: O(1). 

AC Java:

 1 public class Solution {
 2     public boolean isPowerOfTwo(int n) {
 3         if(n <= 0){
 4             return false;
 5         }
 6         while(n%2 == 0){
 7             n /= 2;
 8         }
 9         return n==1;
10     }
11 }

跟上一道Power of ThreePower of FourNumber of 1 Bits.

posted @ 2015-08-15 08:39  Dylan_Java_NYC  阅读(358)  评论(0编辑  收藏  举报