231. Power of Two 2 的幂

@TOC

[LeetCode]

Total Accepted: 71172 Total Submissions: 194399 Difficulty: Easy

# 题目描述

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

Example 1:

``````Input: 1
Output: true
Explanation: 20 = 1
``````

Example 2:

``````Input: 16
Output: true
Explanation: 24 = 16
``````

Example 3:

``````Input: 218
Output: false
``````

# 解题方法

# 二进制

The code above converts number into base base and returns the result as a String. For example, Integer.toString(5, 2) == "101" and Integer.toString(5, 3) == "12".

``````boolean matches = myString.matches("123");

public class Solution {
public boolean isPowerOfThree(int n) {
return Integer.toString(n, 2).matches("^10*\$");
}
}
``````

AC:20ms

``````class Solution(object):
def isPowerOfTwo(self, n):
"""
:type n: int
:rtype: bool
"""
return n > 0 and bin(n).count("1") == 1
``````

# 位运算

``````public class Solution {
public boolean isPowerOfTwo(int n) {
if(n<=0) return false;
return (n & (n-1)) == 0;
}
}
``````

AC:2ms

python解法如下：

``````class Solution(object):
def isPowerOfTwo(self, n):
"""
:type n: int
:rtype: bool
"""
if n <= 0: return False
return n & (n - 1) == 0
``````

# 判断是不是最大2的幂的因数

``````public class Solution {
public boolean isPowerOfTwo(int n) {
if(n<=0) return false;
return (1<<31) % n == 0;
}
}
``````

AC:2ms

# 判断因子是不是只有2

``````class Solution(object):
def isPowerOfTwo(self, n):
"""
:type n: int
:rtype: bool
"""
if n <= 0: return False
while n % 2 == 0:
n /= 2
return n == 1
``````

# 日期

2016/5/1 17:10:28 2018 年 11 月 19 日 —— 周一又开始了