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         // Start typing your Java solution below
 4         // DO NOT write main() function
 5         StringBuffer sb = new StringBuffer();
 6         String l = null;
 7         String s = null;
 8         if(a == null && b == null) return null;
 9         else if(a == "" && b == "") return "";
10         else if(a == "" && b.length() > 0) return b;
11         else if(a.length() > 0 && b == "") return a;
12         if(a.length() > b.length()){
13             l = a;
14             s = b;
15         }else{
16             l = b;
17             s = a;
18         }
19         int j = s.length() - 1;
20         int carry = 0;
21         for(int i = l.length() - 1; i > -1; i --){
22             char c = '0';
23             if(j > -1){
24                 int aa = l.charAt(i) - '0';
25                 int bb = s.charAt(j --) - '0';
26                 c += (aa + bb + carry) % 2;
27                 carry = (aa + bb + carry) / 2;
28             }else{
29                 int aa = l.charAt(i) - '0';
30                 c += (aa + carry) % 2;
31                 carry = (aa + carry) / 2;
32             }
33             sb.insert(0,c);
34         }
35         if(carry == 1)
36             sb.insert(0,"1");
37         return sb.toString();
38     }
39 }

 第二遍:

使用位运算: ^ 异或.

 1 public class Solution {
 2     public String addBinary(String a, String b) {
 3         // Start typing your Java solution below
 4         // DO NOT write main() function
 5         StringBuffer result = new StringBuffer();
 6         int carry = 0;
 7         for(int i = 1; i <= a.length() || i <= b.length(); i ++){
 8             int ac = 0, bc = 0;
 9             if(i <= a.length()) ac = a.charAt(a.length() - i) - '0';
10             if(i <= b.length()) bc = b.charAt(b.length() - i) - '0';
11             result.insert(0, ac ^ bc ^ carry);
12             carry = (ac + bc + carry) > 1 ? 1 : 0;
13         }
14         if(carry > 0) result.insert(0, carry);
15         return result.toString();
16     }
17 }

 

posted on 2013-10-02 07:53  Step-BY-Step  阅读(176)  评论(0编辑  收藏  举报

导航