Fork me on GitHub

牛客网2016校招真题在线编程之懂二进制

 

 先对两个数进行位异或,这样能够得到两个数中有多少位是不同的,然后再数一下这个数中有多少位1就可以了。

 

AC代码:

public class Solution {
    
    /**
     * 获得两个整形二进制表达位数不同的数量
     * 
     * @param m 整数m
     * @param n 整数n
     * @return 整型
     */
    public int countBitDiff(int m, int n) {
        int k = m ^ n;
        int res = 0;
        while(k>0){
            if( (k & 1) == 1) res++;
            k>>=1;
        }
		return res;
    }
    
}

  

 题目地址: https://www.nowcoder.com/practice/ba033b0d1c2f497da1dd04330cc003af?tpId=49&tqId=29232&tPage=1&rp=1&ru=/ta/2016test&qru=/ta/2016test/question-ranking

.

posted @ 2017-11-26 02:18  CC11001100  阅读(206)  评论(0编辑  收藏  举报