461. Hamming Distance

来源:互联网 发布:mac如何查看qq群文件 编辑:程序博客网 时间:2024/06/05 14:47

题目

The Hamming distance between two integers is the number of positions at which the corresponding bits are different.

Given two integers x andy, calculate the Hamming distance.


我的解法

public class Solution {    public int hammingDistance(int x, int y) {        int r = x ^ y; //异或;比特位不同返回1        // 数子转二进制字符串,转字符数组        char[] cArr = Integer.toBinaryString(r).toCharArray();        int count = 0;        for(char c : cArr){            if(c == '1')                count ++;        }        return count;    }}

答案解法

public class Solution {    public int hammingDistance(int x, int y) {        int r = x ^ y;        // 包装类自带方法,计算数值中“1”比特的数量        int count = Integer.bitCount(r);        return count;    }}


0 0
原创粉丝点击