[LeetCode] C++: Simple Question-Bit Operation 231.2 Power

231. Power of 2

Easy difficulty 276

Given an integer, write a function to determine whether it is a power of 2.

Example 1:

Input: 1
 Output: true
 Explanation: 20 = 1

Example 2:

Input: 16
 Output: true
 Explanation: 24 = 16

Example 3:

Input: 218
 Output: false
 
class Solution {
public:
    bool isPowerOfTwo(int n) {
        if(n == 0){
            return false;
        }
        long x = n; //如果x = INT_MIN, x-1会产生溢出,转为位数更多的long 则不会检查溢出
        return (x & (x-1)) == 0;
    }
};
class Solution {
public:
    bool isPowerOfTwo(int n) {
        if(n == 0){
            return false;
        }
        long x = n; //如果x = INT_MIN, x-1会产生溢出,转为位数更多的long 则不会检查溢出
        return (x & (-x)) == x;
    }
};

 How to get the rightmost 1: x & (-x)

How to set the rightmost 1 in binary to 0: x & (x-1) 

Insert picture description here

Insert picture description here

I have stolen the picture, sorry hum~ 

Guess you like

Origin blog.csdn.net/weixin_44566432/article/details/113755235
Recommended