确定需要改变几个位,才能将整数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 }

 

posted on 2014-09-15 15:02  daocaorendeshijie  阅读(185)  评论(0编辑  收藏  举报

导航