Why is my code not working?

  • 0
    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) {
                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.