Simple Java Solution


  • 4
    R

    Iterate over each bit starting from the rightmost bit and working our way left.

    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++) {
                if((n & (1 << i)) != 0) count++;
            }
            return count;
        }
    }

  • 0
    X

    A solution using Java 8 unsigned arithmetic

    public class Solution {
        // you need to treat n as an unsigned value
        public int hammingWeight(int n) {
            int ret = 0;
            while(Integer.compareUnsigned(n, 0) > 0)
            {
                ret+=Integer.remainderUnsigned(n, 2);
                n = Integer.divideUnsigned(n, 2);
            }
            return ret;
        }
    }

  • 0
    Y

    elegant solution!


Log in to reply
 

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