-
Notifications
You must be signed in to change notification settings - Fork 0
/
整数转换.cpp
50 lines (48 loc) · 929 Bytes
/
整数转换.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
/*
题目描述
编写一个函数,确定需要改变几个位,才能将整数A转变成整数B。
给定两个整数int A,int B。请返回需要改变的数位个数。
测试样例:
10,5
返回:4
*/
class Transform {
public:
int calcCost(int A, int B) {
// write code here
int c=A^B;
int count=0;
while(c){
c=c&(c-1);
count++;
}
return count;
}
};
class Transform {
public:
int calcCost(int A, int B) {
// write code here
int c=A^B;
int i=0;
int f=1;
while(f){
if(f&c) i++;
f=f<<1;
}
return i;
}
};
//更佳的解题方式
class Transform {
public:
int calcCost(int A, int B) {
// write code here
int count = 0;
int c;
for (c=A^B;c!=0;c=c&(c-1)){
count ++;
}
return count;
}
};