67. Add Binary

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

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

题目含义:将两个字符串进行二进制加减法。

思路:从最后一位开始依次计算,注意进位

 

 1     public String addBinary(String a, String b) {
 2         StringBuilder sb = new StringBuilder();
 3         int i=a.length()-1,j = b.length() -1;
 4         int carry = 0;
 5         while (i>=0 | j>=0)
 6         {
 7             int sum = carry;
 8             if (i>=0) sum += a.charAt(i--) - '0';
 9             if (j>=0) sum += b.charAt(j--) - '0';
10             sb.append(sum%2);
11             carry = sum/2;
12         }
13         if (carry != 0 ) sb.append(carry);
14         return sb.reverse().toString();      
15     }

 

posted @ 2017-10-16 21:46  daniel456  阅读(108)  评论(0编辑  收藏  举报