码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode 461. Hamming Distance

时间:2017-04-07 00:40:42      阅读:125      评论:0      收藏:0      [点我收藏+]

标签:public   nat   etc   return   ++   异或   leetcode   pre   example   

 要求: 给定两个整数x和y,0 ≤ xy < 231. 求x和y的汉明距离。

Example:

Input: x = 1, y = 4

Output: 2

Explanation:
1   (0 0 0 1)
4   (0 1 0 0)
       ↑   ↑

思路: x,y异或,求结果种1的个数,二进制中1不能被2乘除,所以采用 %2 != 0 来计算1的次数。利用 >>右移位挨个判断。

 

 1 public class Solution {
 2     public int hammingDistance(int x, int y) {
 3        int m = x ^ y;
 4        int i = 0;
 5        while( m > 0){
 6            if(m % 2 != 0){i++;}
 7            m = m>>1;
 8        }
 9        return i;
10    }
11  }

 

leetcode 461. Hamming Distance

标签:public   nat   etc   return   ++   异或   leetcode   pre   example   

原文地址:http://www.cnblogs.com/magicya/p/6676150.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!