Question About Why This Solution Does Not Work


  • 0
    T

    Hi all,

    My algorithm is to check the bit at the right most of the number by AND-ing with 1, then shift that number by 1 bit to the right. Not sure why it doesn't work for MAX INT case. Thanks!

        public int hammingWeight(int n) {
            int count = 0;
            while (n > 0){
                if ((n & 1) == 1){
                    count++;
                }
                n = n >> 1;
            }
            
            return count;
        }

  • 0
    T

    I realized that the problem is when I do while (n > 0), n is negative due to overflowing. When I tried while (n != 0), then it exceeds the time limit. When I changed it to for (int i = 0; i < 32; i++) loop then it worked. Is it a problem with my solution or with the Leetcode platform? Thanks.


  • 0
    M

    Hi, There is a difference between operator ">>" and operator ">>>". ">>" is a sign shift. This means Java will check if the number is a signed integer or not. If it's a signed integer, Java will automatically place "1" at the leftmost bits. On the other hand, ">>>" will fill the leftmost bits with "0" no matter what. So in this case, you should use ">>>" instead of ">>". Hope this will help.


Log in to reply
 

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