十进制转二进制

  如果用传统的方法,除2取余这种方式,不够快。计算机能够可以直接进行位运算。

  我们将要转换的数称作number,需要做的操作就是把number的二进制形式的情况下每次挤出一个数,然后将它保存起来。

  接下来这样操作:

  number>>1  <<1  ^  number

  (^:异或运算,当两者相等时,结果为0,否则为1);

   我们先将number右移一位,然后左移一位,举个例子来说,9二进制表示为1001,右移一位:100,左移一位:1000,此时,去掉了1001的末尾的一位。然后与原来的1001做异或运算:1,即可表示为1001的末尾位。同样,然后(1001>>1)>>1 <<1 ^ (1001>>1),100右移一位然后左移一位即100,100右移一位然后左移一位还是100,两者做异或运算,为0,即是1001的第二位。因此继续下去,直至1001>>n(n为次数)等于0之前,得出的即是二进制数。

  当然实则上,java自带的有这种函数:Integer.toBinaryString(int i),可以直接转换为二进制字符串。

例题:

  将数组中的偶数反转(反转规则,二进制反转,比如11的二进制位1011,则反转为1101)

 1 import java.util.Arrays;
 2 import java.util.Scanner;
 3 
 4 
 5 public class EvenNumberTurn {
 6     public static String toBinary(int number){
 7         String turnAfter=new String();
 8         int temp;
 9         int index=0;
10         if(number==0){
11             return String.valueOf(number);
12         }
13         while(number!=0 && number>>index>0){
14             temp=(((number>>index)>>1) <<1) ^ (number>>index);
15             turnAfter=temp+turnAfter;
16             index++;
17         }
18         return turnAfter.toString();
19     }
20     public static String turnBinary(String number){
21         StringBuffer str=new StringBuffer();
22         str.append(number);
23         String tmp=str.reverse().toString();
24         return tmp;
25     }
26     public static int toDecimal(String a){
27         int decimal=0;
28         for(int j=0, i=a.length()-1;i>=0;i--){
29             decimal=Integer.parseInt(String.valueOf(a.charAt(i))) * (new Double(Math.pow(2,j++))).intValue()+decimal;    
30         }
31         return decimal;
32     }
33     public static int turn(int number){
34         if(number%2==0){
35             String binary=toBinary(number);
36             int turnEven=toDecimal(turnBinary(binary));
37             return turnEven;
38         }
39         else{
40             return number;
41         }
42     }
43     
44     public static void main(String args[]){
45         Scanner read=new Scanner(System.in);
46         int a=Integer.parseInt(read.nextLine());
47         String str=read.nextLine();
48         int[] arr=new int[a];
49         String[] strArr=str.split(" ");
50         for(int i=0;i<a;i++){
51             arr[i]=Integer.parseInt(strArr[i]);
52             arr[i]=turn(arr[i]);
53             System.out.println(arr[i]);
54         }
55         
56         
57     }
58 }
jeyfang
原文地址:https://www.cnblogs.com/jeyfang/p/5723843.html