0

The question is of checking whether the given number has alternating bits or not.

Link to question - https://leetcode.com/problems/binary-number-with-alternating-bits/

Even though dry run of the code shows that logic is correct but answer is wrong and I don't know what am I missing out in the code or what I have done wrong in code that I'm not able to judge.

enter image description here

Dry run of code for 11 -

11's binary representation - 1011

cur = 1011 & 0001 --> cur = 0001
n = 1011>>1 --> n = 0101 
if(n&1 == cur) --> if(0101&0001 == 0001)
return false;
Alan Birtles
  • 32,622
  • 4
  • 31
  • 60
Harsh
  • 234
  • 1
  • 7
  • 6
    Please post a [mre] as text not images – Alan Birtles Oct 26 '20 at 07:06
  • 2
    `==` has higher precedence than `&`.`n&1 == cur` is parsed as `n&(1 == cur)`, not `(n&1) == cur`. Prefer a good introductory [book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) to those nonsensical "competitive" coding websites. – Evg Oct 26 '20 at 07:09
  • 2
    Please don't post images of code. Code is text, thanks. – n. m. could be an AI Oct 26 '20 at 07:11
  • 2
    *I don't know what am I missing out in the code or what I have done wrong in code that I'm not able to judge* -- That's why these "competitive coding" sites are really meant for persons who know the computer language they're going to use, and know it well enough so that they do not need to ask elementary questions about the language being used. They are not teaching sites for learning the language. – PaulMcKenzie Oct 26 '20 at 07:16

1 Answers1

2

You got the solution spot on. It was all about operator precedence creating the bug.

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;
    }
};

Shashank Garg
  • 286
  • 2
  • 7