Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

LeetCode 231. Power of Two #7

Open
Woodyiiiiiii opened this issue Apr 16, 2020 · 0 comments
Open

LeetCode 231. Power of Two #7

Woodyiiiiiii opened this issue Apr 16, 2020 · 0 comments

Comments

@Woodyiiiiiii
Copy link
Owner

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

求一个数是否为2的幂次方。

2的整数次幂对应的二进制数只含有0个或者1个1,所以我们要做的就是判断输入的数的二进制表达形式里是否符合这一条件。有一种corner case需要注意,当输入的数为负数的时候,一定不是2的幂。

当然还有个小问题,就是表达式if (n & 1 == 1)一直报错“ bad operand types for binary operator '&'”,因为相对于位运算符,恒等运算符优先级大一点,这样就导致了“&”左边是int型,右边是boolean型(基础)。

class Solution {
public:
    bool isPowerOfTwo(int n) {
        if (n <= 0) return false;
        bool hasOne = false;
        for (int i = 0; i < 32; ++i) {
            if (n & 1 == 1) {
                if (hasOne) {
                    return false;
                }
                else {
                    hasOne = true;
                }
            }
            n >>= 1;
        }
        return true;
    }
};

参考资料:
LeetCode原题

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant