[LeetCode] 231. Power of Two 2的次方数

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

Example 1:

Input: 1
Output: true

Example 2:

Input: 16
Output: true

Example 3:

Input: 218
Output: false

给一个整数,写一个函数来判断它是否为2的次方数。

利用计算机用的是二进制的特点,用位操作,此题变得很简单。

2的n次方的特点是:二进制表示中最高位是1,其它位是0,

1  2   4     8     16    ....

1 10 100 1000 10000 ....

解法:位操作(Bit Operation),用右移操作,依次判断每一位的值,如果只有最高位是1,其余位都是0,则为2的次方数。

解法2: 位操作(Bit Operation),原数减1,则最高位为0,其余各位都变为1,把两数相与,就会得到0。

解法3: 用数学函数log

Java:

public boolean isPowerOfTwo(int n) {
    if(n<=0) 
        return false;
 
    while(n>2){
        int t = n>>1;
        int c = t<<1;
 
        if(n-c != 0)
            return false;
 
        n = n>>1;
    }
 
    return true;
}  

Java:

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

Java:

public boolean isPowerOfTwo(int n) {
    return n>0 && n==Math.pow(2, Math.round(Math.log(n)/Math.log(2)));
} 

Python:

class Solution:
    # @param {integer} n
    # @return {boolean}
    def isPowerOfTwo(self, n):
        return n > 0 and (n & (n - 1)) == 0

Python:

class Solution2:
    # @param {integer} n
    # @return {boolean}
    def isPowerOfTwo(self, n):
        return n > 0 and (n & ~-n) == 0  

C++:

class Solution {
public:
    bool isPowerOfTwo(int n) {
        int cnt = 0;
        while (n > 0) {
            cnt += (n & 1);
            n >>= 1;
        }
        return cnt == 1;
    } 
};  

C++:

class Solution {
public:
    bool isPowerOfTwo(int n) {
        return (n > 0) && (!(n & (n - 1)));
    } 
};

  

 

类似题目:

[LeetCode] Number of 1 Bits

[LeetCode] Power of Four

[LeetCode] 326. Power of Three

 

All LeetCode Questions List 题目汇总

转载于:https://www.cnblogs.com/lightwindy/p/9049100.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值