Leetcode-Add Binary

LiBlog發表於2014-11-29

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

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

Solution:

 1 public class Solution {
 2     public String addBinary(String a, String b) {
 3         String res = "";
 4         int index1 = a.length()-1;
 5         int index2 = b.length()-1;
 6         int carry = 0;
 7         while (index1>=0 || index2>=0){
 8             int val = 0;
 9             if (index1<0){
10                 val = (b.charAt(index2)=='0')? 0 : 1;
11                 val += carry;                
12                 index2--;
13             } else if (index2<0){
14                 val = (a.charAt(index1)=='0')? 0 : 1;
15                 val += carry;                
16                 index1--;
17             } else {
18                 val = (a.charAt(index1)=='0')? 0 : 1;
19                 val += (b.charAt(index2)=='0')? 0 : 1;
20                 val += carry;                
21                 index1--;
22                 index2--;
23             }
24             carry = val/2;
25             val = val%2;
26             res = Integer.toString(val)+res;
27         }
28         if (carry>0) res = Integer.toString(carry)+res;
29         return res;
30     }
31 }

 

相關文章