231. Power of Two*

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.

Example 1:

Input: 1
Output: true 
Explanation: 20 = 1

Example 2:

Input: 16
Output: true
Explanation: 24 = 16

Example 3:

Input: 218
Output: false

C++ 实现 1

使用递归的方法实现.

class Solution {
public:
    bool isPowerOfTwo(int n) {
        if (n == 1) return true;
        if (n % 2 == 1 || n == 0) return false;
        n /= 2;
        return isPowerOfTwo(n);
    }
};

C++ 实现 2

使用移位的方法实现. 来自 LeetCode Submission.

class Solution {
public:
    bool isPowerOfTwo(int n) {
        if(n == 0) {
            return false;
        }
        while(n != 1) {
            if(n & 1) {
                return false;
            } else {
                n >>= 1;
            }
        }
        return true;
    }
};

C++ 实现 3

Using n&(n-1) trick

Power of 2 means only one bit of n is ‘1’, so use the trick n&(n-1)==0 to judge whether that is the case

class Solution {
public:
    bool isPowerOfTwo(int n) {
        if(n<=0) return false;
        return !(n&(n-1));
    }
};
发布了455 篇原创文章 · 获赞 8 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/Eric_1993/article/details/104872992
今日推荐