My Java AC solution


  • 0
    T

    Key point is using 'Integer.toBinaryString()'

    public int hammingDistance(int x, int y) {
        int res = x ^ y;
        String s = Integer.toBinaryString(res);//key point. change Integer to binary string
        int count = 0;
        for (int i = 0; i < s.length(); i++){
            if (s.charAt(i) == '1')
                count++;
        }
        return count;
    }
    
    public int hammingDistance(int x, int y) {
        int res = x ^ y;
        String s = Integer.toBinaryString(res);//key point. change Integer to binary string
        s = s.replaceAll("0", "");//key point: replaceAll
        return s.length();
    }

Log in to reply
 

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