461. Hamming Distance【数学|位运算】
生活随笔
收集整理的這篇文章主要介紹了
461. Hamming Distance【数学|位运算】
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
2017/3/14 15:23:55
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.
?
題目要求:求兩個數(shù)字二進制位中同一位置不同bit的個數(shù)。
解法1 ?Java? ? 利用1的移位依次匹配是否對應(yīng)位為1,統(tǒng)計為1的個數(shù)。
?
public class Solution {public int hammingDistance(int x, int y) {x ^= y;int count = 0;for ( int i=0;i<32;i++ )count = (1<<i & x ) !=0 ? count+1 : count;return count;} }解法2 Java ? 利用 a &= a-1 依次去掉最后一個1,統(tǒng)計循環(huán)次數(shù)。
public class Solution {public int hammingDistance(int x, int y) {x ^= y;int count = 0;while( x != 0 ){x &= x - 1;count++;}return count;} }
轉(zhuǎn)載于:https://www.cnblogs.com/flyfatty/p/6624801.html
總結(jié)
以上是生活随笔為你收集整理的461. Hamming Distance【数学|位运算】的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 利用PPT要怎样制作文字弹幕特效
- 下一篇: DevExpress.Utils.Too