My short java solution

  • -2

    public class Solution {

    // you need to treat n as an unsigned value
    public int hammingWeight(int n) {
        	String num=Integer.toBinaryString(n);
        	int N=0;    
        	for(int i=0;i<num.length();i++)
        		if(num.charAt(i)== '1') N=N+1; 
    		return N;


  • 0

    Don't work with strings! What if you do "n = n & (n - 1)"? Write it down and check the result for any number.

Log in to reply

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