首页 > 其他 > 详细

确定需要改变几个位,才能将整数A转变为整数B

时间:2014-09-15 15:46:49      阅读:233      评论:0      收藏:0      [点我收藏+]
 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 }

 

确定需要改变几个位,才能将整数A转变为整数B

原文:http://www.cnblogs.com/luoweiKnowledge/p/3972843.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!