why n % 2 == 1 doesn't work here


  • 0
    Y

    Can someone please tell me why n % 2 == 1 produces wrong result on test case 4294967295 (11111111111111111111111111111111)? After I changed to (n & 1) == 1, it passed. Thanks!

    public class Solution {
        // you need to treat n as an unsigned value
        public int hammingWeight(int n) {
            int count = 0;
            while (n != 0) {
                if (n % 2 == 1) {
                    count++;
                }
                n >>>= 1;
            }
            return count;
        }
    }
    

  • 0
    L

    (-3)%2 = -1
    int is signed in java.


Log in to reply
 

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