给定两个整数A和B。编写函数,返回将整数A转变成整数B所需要改变的数位个数。
测试样例:
10,5
返回:4
import java.util.*; public class Transform { public int calcCost(int A, int B) { // write code here String a = buwei(totwo(Math.abs(A))); String b = buwei(totwo(Math.abs(B))); if(A<0) { a = fu(a); } if(B<0) { b = fu(b); } return change(a,b); } private int change(String a,String b) { int out = 0; for(int i=0;i<32;i++) { if(a.charAt(i)!=b.charAt(i)) { out++; } } return out; } private String fu(String n){ String out = ""; for(int i=0;i<n.length();i++) { if(n.charAt(i)=='1') { out+=0; } else{ out+=1; } } return out; } private String buwei(String n) { final int wei = 32; String out = n; for(int i=0;i<(wei-n.length());i++) { out = "0"+out; } return out; } private String totwo(int n) { String out = ""; while(n>=2) { out = n%2 + out; n = n/2; } return n + out; } }
首先A转化B要改变多少位,即A和B有多少位不同,异或相同则为0,不同为1,接下来就是求一个数的二进制中的1的个数,剑指offer原题 class Transform { public: int calcCost(int A, int B) { int num=A^B; int count=0; while(num) { count++; num=num&(num-1); } return count++; } };
# -*- coding:utf-8 -*-
class Transform:
def calcCost(self, A, B):
A=bin(A).replace("0b","").rjust(32,"0")
B=bin(B).replace("0b","").rjust(32,"0")
return sum(map(lambda c:A[c]!=B[c],range(32)))
return sum(map(lambda c:bin(A).replace("0b","").rjust(32,"0")[c]!=bin(B).replace("0b","").rjust(32,"0")[c],range(32)))
//方法一:就是喜欢这么暴力 public int calcCost(int A, int B) { int n=A^B,count=0; while(n!=0){ n=n&n-1;//把最右面一个1给他置零 count++; } return count; } //方法二: public int calcCost(int A, int B) { int n=A^B,count=0,index=1;; while(index!=0){ count+=(index&n)==0?0:1; index<<=1; } return count; }
import java.util.*; //直接用Integer内置的bitCount来计算二进制里1的个数 public class Transform { public int calcCost(int A, int B) { int sum=A^B; return Integer.bitCount(sum); } }参考:http://blog.csdn.net/sinat_22797429/article/details/75451808
/* * 思路:比较A和B每位上数字是否相同,使用异或方式比较 * 获取每位数字的方法:A-(A >>> 1 << 1),A无符号右移1位再左移一位,原数A减去该数,得到最低位的值 * 循环内进行异或比较后,将A >>> 1,因为最低位已比较完毕,故到较高一位比较 */ public int calcCost(int A, int B) { // write code here int res = 0; while(A != 0 || B != 0){ int Abit = A - (A >>> 1 << 1); int Bbit = B - (B >>> 1 << 1) ; if((Abit ^ Bbit) == 1){ res++; } A = A >>> 1; B = B >>> 1; } return res; }