Java solution very easy to understand


  • 0
    L

    public class Solution {
    // you need to treat n as an unsigned value
    public int hammingWeight(int n) {

    String str = Integer.toBinaryString(n);
    
    Character[] res = new Character[str.length()];
    for(int i=0;i<str.length();i++){
        res[i]=str.charAt(i);
    }
    int count = 0;
    for(int i=0;i<res.length;i++){
    	if(str.charAt(i)=='1'){
    		count++;
    	}
    }
    return count;
    }
    

    }


Log in to reply
 

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