67. Add Binary【LeetCode】

67. 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         String res ="";
 4         int l1=a.length()-1;
 5         int l2=b.length()-1;
 6         
 7         int carry=0;
 8         for(int i=l1,j=l2;i>=0||j>=0;i--,j--){
 9             int sum=carry;
10             sum+=(i>=0)?(int)(a.charAt(i)-'0'):0;
11             sum+=(j>=0)?(int)(b.charAt(j)-'0'):0;
12             res =sum%2+res;
13             carry=sum/2;
14             
15         }
16         if(carry!=0){
17             res=carry+res;
18         }
19         return res;
20     }
21 }

 

posted @ 2017-08-11 00:34  这个手杀不太0  阅读(179)  评论(0编辑  收藏  举报