461. Hamming Distance
来源:互联网 发布:vscode 支持xp吗 编辑:程序博客网 时间:2024/05/17 07:32
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.
Note:
0 ≤ x
, y
< 231.
Example:
Input: x = 1, y = 4Output: 2Explanation:1 (0 0 0 1)4 (0 1 0 0) ? ?The above arrows point to positions where the corresponding bits are different.解题思路:1.C语言中,x & 1从命令的角度讲,是将x的每一bit(2进制中的1和0都占一个bit)与0001的每一bit做与运算."&"是"与运算"的意思,1&1=1,其他情况(1&0,0&1,0&0)都=0.从逻辑的角度来讲,这个命令就是取x的最左边一位.例如x是0011,x&1得到0001,如果x是0110,x&1得到0000. x ^= y是个异或并赋值的操作符。属于位操作符。二者不同返回1,相同返回 0;意思是 x与y异或的结果存入 x。假如 x的二进制是 00000000 00000000 00000000 11111111; 或者更长y的二进制是 00000000 00000000 11111111 00001111;则 x^=y;之后 x 的二进制是 00000000 00000000 11111111 11110000;x >>= 1表示将n的二进制表示向右移动一位再赋值给n2.Java解法
- int hammingDistance(int x, int y) {
- int count=0;
- while (x || y)
- {
- if ((x & 1) ^ (y & 1))
- {
- count++;
- x >>= 1;
- y >>= 1;}
- }
- return count;
- }
1 public int hammingDistance(int x, int y) {2 int xor = x ^ y, count = 0;3 for (int i=0;i<32;i++) count += (xor >> i) & 1;4 return count;5 }
阅读全文
0 0
- LeetCode 461. Hamming Distance
- 461. Hamming Distance
- 【Leetcode】461. Hamming Distance
- 461. Hamming Distance
- LeetCode 461. Hamming Distance
- 461. Hamming Distance
- LeetCode - 461. Hamming Distance
- 461. Hamming Distance*
- LeetCode-461. Hamming Distance
- 461. Hamming Distance
- 【LeetCode】 461. Hamming Distance
- 461. Hamming Distance
- 461. Hamming Distance#1
- 461. Hamming Distance
- Leetcode-461. Hamming Distance
- 461. Hamming Distance
- Leetcode 461. Hamming Distance
- 461. Hamming Distance
- Oracle12C--包(四十七)
- 怎么验证交易是否成功
- 线控耳机
- zabbix监控windows进程
- 润乾报表js获取下拉数据集下拉框的显示值
- 461. Hamming Distance
- 一些小问题
- HTTP详解--提升传输速率(六)
- ${pageContext.request.contextPath} JSP取得绝对路径
- 仿windows桌面气泡
- Linux实用60命令详解
- HTTP详解--发送多种数据的多部分对象集合(七)
- Hello CSDN
- Volley实现图片加载功能