Java toBinaryString solution


  • 0
    H
    public int hammingWeight(int n) {
    	int count = 0;
    	String str = Integer.toBinaryString(n);
    	for(int i=0; i<str.length(); i++) {
    		if(str.charAt(i)=='1') {
    			count++;
    		}
    	}
    	return count;
    }

  • 0
    G

    same as
    int count = 0;
    for (int i = 0; i < 32; ++i)
    if ((n & (1 << i)) != 0)
    ++count;
    return count;


Log in to reply
 

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