Why is my code not working?


  • 0
    L
    public class Solution {
        // you need to treat n as an unsigned value
        public int hammingWeight(int n) {
            int countOnes=0, countBits=0;
            while(countBits <= 32) {
                if((n&1) == 1) {
                    countOnes++;
                }
                countBits++;
                n = n >> 1;
            }
            return countOnes;
        }
    }
    

  • 0

    @leetcodeuserx You should adopt a mask to check each bit from the start to the end, instead of shifting the original number which will be unstable since it's int instead of unsigned int (right shifting is the problem here).


Log in to reply
 

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