# [231] Power of Two

### 1. 题目描述

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

### 3. Code

// Code1(Failed)
public class Solution {
//当n = 536870912时，精度出现问题
public boolean isPowerOfTwo(int n) {
double result = Math.log(n) / Math.log(2);
int i = (int)result;
return (result - i) == 0; // 判断result是不是整数
}
}
// Code2（Accept）
public class Solution {
public boolean isPowerOfTwo(int n) {
if (n == 0)
return false;
// n取余2为0
while(n%2 == 0)
{
n = n/2;
}
if (n == 1)
return true;
return false;
}
}
// Code3
public class Solution {
public boolean isPowerOfTwo(int n) {
// 如果n=0返回false，else返回n按位与n-1
// 10000 & 01111 = 0
return n == 0 ? false : n & (n-1) == 0;
}
}

#### power of two

2015-07-06 21:00:09

#### LCP342 LeetCode 342. Power of Four

2016-06-08 15:27:34

#### 342.Power of Four

2017-08-29 06:28:02

#### 326.Power of Three

2017-08-29 06:27:19

#### LeetCode之342，Power of Four

2017-02-04 11:37:46

#### LeetCode 231: Power of Two

2015-07-06 18:34:20

#### leetcode 231: Power of Two

2015-07-07 05:01:24

#### Leetcode#231_power of two

2016-04-07 21:39:28

#### [LeetCode-231] Power of Two（判断一个数是不是2的若干次幂）

2015-09-14 19:59:45

#### Power of Two(leetcode 231)

2015-07-11 20:06:10