Add Binary

Add Binary

 

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

For example,
a = "11"
b = "1"
Return "100".

 1 public class Solution {
 2     public String addBinary(String a, String b) {
 3         char num1[] = a.toCharArray();
 4         char num2[] = b.toCharArray();
 5         int result[] = new int[Math.max(a.length(), b.length()) + 1];//保存结果
 6         int i = num1.length - 1;
 7         int j = num2.length - 1;
 8         int k = result.length - 1;
 9         while(i >= 0 && j >= 0){
10             if(num1[i] == '1' && num2[j] == '1')
11                 result[k--] = 2;
12             else if(num1[i] == '0' && num2[j] == '0')
13                 result[k--] = 0;
14             else
15                 result[k--] = 1;
16             i--;
17             j--;
18         }//至少有一个计算完成
19         while(i >= 0){
20             result[k--] = num1[i--] - '0';
21         }
22         while(j >= 0)
23             result[k--] = num2[j--] - '0';
24         k = result.length - 1;
25         while(k > 0){
26             if(result[k] / 2 == 1)
27             {
28                 result[k - 1] += 1;
29                 result[k] %= 2;
30             }
31             k--;
32         }
33         String ret = "";
34         if(result[0] != 0){
35             for(i = 0; i < result.length; i++)
36                 ret += String .valueOf(result[i]);
37         }
38         else
39         {
40             for(i = 1; i < result.length; i++)
41                 ret += String .valueOf(result[i]);
42         }
43         return ret;
44     }
45 }

 

posted on 2014-11-10 21:37  luckygxf  阅读(129)  评论(0编辑  收藏  举报

导航