Why my code is wrong for 4294967295 (11111111111111111111111111111111)?


  • 0
    N
    public class Solution {
        // you need to treat n as an unsigned value
        public int hammingWeight(int n) {
            int count = 0;
            for (int i = 0; i < 32; i++) {
                int temp = n % 2;
                if (temp == 1) {
                    count++;
                }
                n = n >>> 1;
            }
            return count;
        }
    }
    

    Why the answer for 4294967295 (11111111111111111111111111111111) is 31 but not 32?


  • 0

    Print each temp and you'll see.


  • -1
    A

    11111111111111111111111111111111>>>1 is 10111111111111111111111111111111,
    11111111111111111111111111111111>>1 is 11111111111111111111111111111111.

    So it's right to use ">>>" instead of ">>", but the sign bit should be considered additionally.


  • 0
    J

    11111111111111111111111111111111>>>1 is
    1111111111111111111111111111111
    not
    10111111111111111111111111111111

    The problem is 11111111111111111111111111111111 is essentially "-1" and "-1 % 2" is "-1" not 1, so the first iteration will not increment the count.


  • 0
    J

    The problem is 11111111111111111111111111111111 is essentially "-1" and "-1 % 2" is "-1" not 1, so the first iteration will not increment the count.


  • 0
    A

    Yes, you're right. Thank you for your correction.


Log in to reply
 

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