两个二进制中不同位的个数

来源:互联网 发布:相册网站设计源码 编辑:程序博客网 时间:2024/05/27 14:15

今天在牛客网刷题,现在要写的这题(2015年小米暑期实习面试题)其实蛮简单的,可是因为自己编写的经验不够,所以用了比较蠢的法子,后来看到他人公布的解法觉得眼前一亮。所以要记下来。

题目要求:


我的解法是,用Integer类里的方法把十进制转换成二进制,将得到的二进制String转换成char数组,再从后往前比较,比较至短字符串的开始处,再对较长的字符串前面的1进行统计。真的是很复杂,如下所示:

public static int countBitDiff(int m, int n) {String sm=Integer.toBinaryString(m);String sn=Integer.toBinaryString(n);char[] cm=sm.toCharArray();char[] cn=sn.toCharArray();int len=Math.min(cm.length, cn.length);int cha=Math.abs(sm.length()-sn.length());int counter=0;if (cm.length<cn.length) {for (int i = len-1; i >-1; i--) {if (cm[i]!=cn[i+cha]) {counter++;}}}else {for (int i = len-1; i >-1; i--) {if (cn[i]!=cm[i+cha]) {counter++;}}}String sub="";if (sm.length()>sn.length()) {sub=sm.substring(0,cha);}else {sub=sn.substring(0,cha);}char[] csub=sub.toCharArray();for (int i = 0; i < csub.length; i++) {if (csub[i]=='1') {counter++;}}return counter;    }
我提交通过之后,看到了别人的思路,是先异或,才反应过来,是的,本来就是求不同,直接用异或,然后再求异或后的数的1的个数就好了。昨天的那道题正好就是求一个数中1的个数的。

所以可以用一句话解决这个问题,如下:

return Integer.bitCount(m^n);
就是这样。霍霍。


0 0
原创粉丝点击