整数转化 牛客网 程序员面试金典 C++ Python
题目描述
编写一个函数,确定需要改变几个位,才能将整数A转变成整数B。
给定两个整数int A,int B。请返回需要改变的数位个数。
测试样例:
10,5
返回:4
C++
class Transform {
public:
//run:3ms memory:480k
int calcCost(int A, int B) {
int C = A^B;
return getOneCount(C);
}
int getOneCount(int x){
int count = 0;
for(;x;count++) x = x & (x-1);
return count;
}
};
Python
class Transform:
#run:32ms memory:5728k
def calcCost(self, A, B):
C = A^B
return self.getOneCount(C)
def getOneCount(self,x):
count =0
while x:
count += 1
x = x & (x -1)
return count
转载于:https://www.cnblogs.com/vercont/p/10210321.html
相关资源:数据结构—成绩单生成器