标签:public nat etc return ++ 异或 leetcode pre example
要求: 给定两个整数x和y,0 ≤ x
, y
< 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