首页 > 编程语言 > 详细

Leetcode 461. Hamming Distance JAVA语言

时间:2017-01-04 17:31:26      阅读:311      评论:0      收藏:0      [点我收藏+]

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

Given two integers x and y, calculate the Hamming distance.

PS:求海明距离。

思路:就是求x和y二进制的异或中的1的个数

public class Solution {
    public int hammingDistance(int x, int y) {
        // String x1=Integer.toBinaryString(x);
        // String y1=Integer.toBinaryString(y);
        int tem=x^y;
        int count=0;
        String str=Integer.toBinaryString(tem);
        for(int i=0;i<str.length();i++){
            if(str.charAt(i)==‘1‘){
                count++;
            }
        }
        // System.out.println(count);
        
        return count;
    }
}


Leetcode 461. Hamming Distance JAVA语言

原文:http://fulin0532.blog.51cto.com/6233825/1888736

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!