二进制求和

给定两个二进制字符串,返回他们的和(用二进制表示)。

样例

a = 11

b = 1

返回 100

 1 public class Solution {
 2     /**
 3      * @param a a number
 4      * @param b a number
 5      * @return the result
 6      */
 7     public String addBinary(String a, String b) {
 8         // Write your code here
 9         long temp1 = changeLong(a);
10         long temp2 = changeLong(b);
11         long temp3 = temp1 + temp2;
12         String s = changeBin(temp3);
13         return s;
14     }
15     
16      /**
17      * 把一个二进制的字符串变成一个十进制的long型的数字。
18      * @param a
19      * @return
20      */
21     public static long changeLong(String a)
22     {
23         if(a =="0")
24         {
25             return 0L;
26         }
27         long sum = 0L;
28         long l = Long.parseLong(a);
29         List<Long> list = new ArrayList<>();
30         int count = 0;
31         while( l > 0)
32         {
33             long temp = l % 10;
34             list.add(temp);
35             l /= 10;
36             count++;
37         }
38 
39         for(int i = count-1; i >= 0; i--)
40         {
41             double pow = Math.pow(2, i);
42             sum += list.get(i) * Math.pow(2,i);
43         }
44         return sum;
45     }
46 
47     /**
48      * 将一个十进制的数字变成二进制的字符串。
49      * @param a
50      * @return
51      */
52     public String changeBin(long a)
53     {
54         if(a == 0L)
55         {
56             return "0";
57         }
58         List<Long> list = new ArrayList<>();
59         int count = 0;
60         while(a > 0)
61         {
62             long temp = a % 2;
63             list.add(temp);
64             count++;
65             a /= 2;
66         }
67         StringBuffer sbf = new StringBuffer();
68         for(int i = list.size()-1; i >= 0; i--)
69         {
70             sbf.append(list.get(i));
71         }
72         return sbf.toString();
73     }
74 }
原文地址:https://www.cnblogs.com/zkycode/p/7007218.html