Java,easy to understand


  • 0
    P
    public static int hammingWeight(int n) {
    	String hexString = Integer.toBinaryString(n);
    	char[] array = hexString.toCharArray();
    	int result = 0;
    	for (int i = 0; i < array.length; i++) {
    		if(array[i] == '1'){
    			result ++;
    		}
    	}
    	return result;
    }

  • 0
    L

    My solution as follows:

    public int hammingWeight(int n) {
            int count=0;
            while(n!=0){
                if((n&1)!=0){
                    count++;
                }
                 n=n>>>1;
            }
            return count;
        }
    

    it's 2ms, but it says that beats 15% answers. I want to know the faster solution.


Log in to reply
 

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