Add Binary

Given two binary strings, return their sum (also a binary string).

Example

a = 11

b = 1

Return 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         if (a == null || a.length() == 0) {
 9             return b;
10         }
11         if (b == null || b.length() == 0) {
12             return a;
13         }
14         if (b.length() > a.length()) {
15             String temp = a;
16             a = b;
17             b = temp;
18         }
19         int carry = 0;
20         int indexA = a.length() - 1;
21         int indexB = b.length() - 1;
22         StringBuilder sb = new StringBuilder();
23         while(indexB >= 0 && indexA >= 0) {
24             int temp = (int)(a.charAt(indexA) - '0') + (int)(b.charAt(indexB) - '0') + carry;
25             carry = temp / 2;
26             sb.append(temp % 2);
27             --indexA;
28             --indexB;
29         }
30         while (indexA >= 0) {
31             int temp = (int)(a.charAt(indexA) - '0')  + carry;
32             carry = temp / 2;
33             sb.append(temp % 2);
34             --indexA;
35         }
36         if (carry == 1) {
37             sb.append("1");
38         }
39         return sb.reverse().toString();
40     }
41 }

 

posted @ 2016-06-03 08:51  YuriFLAG  阅读(89)  评论(0)    收藏  举报