Skip to content

Commit d6f61f1

Browse files
committed
编写一个函数,确定需要改变几个位,才能将整数A转变成整数B。
给定两个整数int A,int B。请返回需要改变的数位个数。 测试样例: 10,5 返回:4
1 parent 0cbf535 commit d6f61f1

1 file changed

Lines changed: 24 additions & 0 deletions

File tree

src/Transform.java

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
/*
2+
* 编写一个函数,确定需要改变几个位,才能将整数A转变成整数B。
3+
* 给定两个整数int A,int B。请返回需要改变的数位个数。
4+
* 测试样例:
5+
* 10,5
6+
* 返回:4
7+
*/
8+
public class Transform {
9+
public int calcCost(int A, int B) {
10+
int a=A^B;
11+
int count=0;
12+
while(a!=0){
13+
if((a&1)==1){
14+
count++;
15+
}
16+
a>>>=1;
17+
}
18+
return count;
19+
}
20+
public static void main(String[] args) {
21+
Transform tf = new Transform();
22+
System.out.println(tf.calcCost(10, 5));
23+
}
24+
}

0 commit comments

Comments
 (0)