全世界上有10种人,一种懂二进制,一种不懂。那么你知道两个int32整数m和n的二进制表达,有多少个位(bit)不同么? 输入例子: 1999 2299 输出例子: 7
世界上有10种人,一种懂二进制,一种不懂。那么你知道两个int32整数m和n的二进制表达,有多少个位(bit)不同么? 输入例子: 1999 2299 输出例子: 7
这是小米2015年暑假实习生第一道笔试题,其实不难,主要用到移位操作和或运算符就可以搞定,具体代码如下:
/*世界上有10种人,一种懂二进制,一种不懂。那么你知道两个int32整数m和n的二进制表达,有多少个位(bit)不同么? 输入例子: 1999 2299 输出例子: 7 */ #include<stdio.h> int countBitDiff(int m, int n) { int data=1; int a,b; int count=0; for(int i=0;i<31;i++) { a=m&data; b=n&data; if(a!=b) { count++; } m=m>>1; n=n>>1; } return count; } void main() { printf("-->%d\n",countBitDiff(1999,2299)); }