Where is the undefined behavior? Hamming Distance


  • 0
    T

    I'm currently doing simple problems on leetcode on c++ and am getting wrong answers when it's actually right. I know it's right because I run the same code on java and it works.

    Reading further, this looks like undefined behavior, but I honestly am not using static variables, so I'd like some help identifying what I'm doing wrong so I can recognize these issues in the future.

    Thanks!

    class Solution {
        
    public:
        int hammingDistance(int x, int y) {
            int answer;
            
            while( x != 0 || y != 0){
                
                if( (x%2) != (y%2) )
                    answer++;
                
                x/=2;
                y/=2;
            }
            
            return answer;
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.