带有交替位的二进制数,答案错误

问题描述

问题是检查给定数字是否具有交替位。

链接到问题-https://leetcode.com/problems/binary-number-with-alternating-bits/

即使代码的空运行表明逻辑是正确的,但答案是错误的,我不知道代码中缺少什么,或者我无法判断的代码做错了什么。

enter image description here

试运行11的代码-

11的二进制表示形式-1011

cur = 1011 & 0001 --> cur = 0001
n = 1011>>1 --> n = 0101 
if(n&1 == cur) --> if(0101&0001 == 0001)
return false;

解决方法

您已找到解决方案。 一切都与操作员优先级造成的错误有关。

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