Leetcode 461. Hamming Distance

来源:互联网 发布:ntp服务器修改端口 编辑:程序博客网 时间:2024/05/29 14:20
public class Solution {    private final int LENGTH = 32;    public int hammingDistance(int x, int y) {        int[] bits_x = new int[LENGTH];        int[] bits_y = new int[LENGTH];                // calculate binary codes for x and y        int k = 0;        while (x > 0) {            bits_x[k++] = x%2;            x /= 2;        }        k = 0;        while (y > 0) {            bits_y[k++] = y%2;            y /= 2;        }                // count the distance        int distance = 0;        for (int i=0; i<LENGTH; i++) {            if (bits_x[i] != bits_y[i])                distance++;        }                return distance;    }}

0 0
原创粉丝点击