Add Binary

 1 public class Solution {
 2     public String addBinary(String a, String b) {
 3         int len1 = a.length();
 4         int len2 = b.length();
 5         StringBuilder sb = new StringBuilder();
 6         int p1 = len1-1;
 7         int p2 = len2 -1;
 8         int carry = 0;
 9         while(p1>=0&&p2>=0){
10             int temp = a.charAt(p1)-'0'+b.charAt(p2)-'0'+carry;
11             carry = temp/2;
12             sb.append(temp%2);
13             p1--;p2--;
14         }
15         while(p1>=0){
16             int temp = a.charAt(p1)-'0'+carry;
17             carry = temp/2;
18             sb.append(temp%2);
19             p1--;
20         }
21         while(p2>=0){
22             int temp = b.charAt(p2)-'0'+carry;
23             carry = temp/2;
24             sb.append(temp%2);
25             p2--;
26         }
27         if(carry>0)
28             sb.append(carry);
29         return sb.reverse().toString();
30     }
31 }
View Code

 

posted @ 2014-02-06 14:32  krunning  阅读(96)  评论(0编辑  收藏  举报