确定需要改变几个位,才能将整数A转变为整数B
生活随笔
收集整理的这篇文章主要介绍了
确定需要改变几个位,才能将整数A转变为整数B
小编觉得挺不错的,现在分享给大家,帮大家做个参考.
1 /*确定需要改变几个位,才能将整数A转变为整数B
2 * 找出两个数之间位有哪些不同,可以使用异或操作即可
3 * 在异或操作的结果中,每个1都代表A和B相应位是不一样的
4 * 因此只要数一数异或之后又几个位为1就可以知道需要改变几个位
5 *
6 * */
7 public class BitsNum {
8 public int bitSwapRequired(int a,int b)
9 {
10 int count=0;
11 for(int c=a^b;c!=0;c=c>>1)
12 {
13 count+=c&1;
14 }
15 return count;
16 }
17
18 public static void main(String[] args) {
19 // TODO Auto-generated method stub
20 BitsNum bit = new BitsNum();
21 int num = bit.bitSwapRequired(2, 4);
22 System.out.println(num);
23 }
24
25 }
转载于:https://www.cnblogs.com/luoweiKnowledge/p/3972843.html
总结
以上是生活随笔为你收集整理的确定需要改变几个位,才能将整数A转变为整数B的全部内容,希望文章能够帮你解决所遇到的问题。
- 上一篇: 个人推荐书单
- 下一篇: Hessian 初探