[leetcode]Add Binary

Add Binary

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

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

 

算法思路:

模拟二进制加法,跟十进制木有区别,将a,b转置(不转置的话,倒着遍历也是同样道理),这样就可以从低位到高位逐级递加了

 1 public class Solution {
 2     public String addBinary(String a, String b) {
 3         if( a == null || a.length() == 0) return b;
 4         if( b == null || b.length() == 0) return a;
 5         // assume that b.length is longer
 6         if(b.length() < a.length()) return addBinary(b, a);
 7         StringBuilder br = new StringBuilder(b).reverse();
 8         StringBuilder ar = new StringBuilder(a).reverse();
 9         int leap = 0;
10         for(int i = 0; i < br.length(); i++){
11                int aNum = (i < ar.length())? (ar.charAt(i) == '0' ? 0 : 1) : 0;
12             int bNum = br.charAt(i) == '0' ? 0 : 1;
13             if(aNum + bNum + leap == 1){
14                 br.setCharAt(i, '1');
15                 leap = 0;
16             }else if(aNum + bNum + leap == 2){
17                 br.setCharAt(i, '0');
18                 leap = 1;
19             }else if(aNum + bNum + leap == 3){
20                 br.setCharAt(i, '1');
21                 leap = 1;
22             }
23         }
24         if(leap == 1) br.append('1');
25         return br.reverse().toString();
26     }
27 }

posted on 2014-07-24 21:08  喵星人与汪星人  阅读(310)  评论(0编辑  收藏  举报