Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b
= "1"
Return "100"
.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33 |
public class Solution { /**The program is used to calculate the sum of two binaries. This is a fundamental problem.<br> * @param a --binary string as the first operand * @param b --binary string as the second operand * @return a string --the sum of binary a and b * @author Averill Zheng * @version 2014-06-03 * @since JDK 1.7 */ public
String addBinary(String a, String b) { int
lengthOfA = a.length(), lengthOfB = b.length(); StringBuffer resultBuffer = new
StringBuffer(); int
carry = 0 ; while (lengthOfA > 0
&& lengthOfB > 0 ){ int
sum = (a.charAt(lengthOfA - 1 ) - ‘0‘ ) + (b.charAt(lengthOfB - 1 )- ‘0‘ ) + carry; carry = sum / 2 ; resultBuffer.insert( 0 , sum % 2 ); --lengthOfA; --lengthOfB; } String remaining = (lengthOfA == 0 )? b : a; int
index = (lengthOfA == 0 ) ? lengthOfB : lengthOfA; while (index > 0 ){ int
sum = (remaining.charAt(index - 1 ) - ‘0‘ ) + carry; carry = sum / 2 ; resultBuffer.insert( 0 , sum % 2 ); --index; } if (carry != 0 ) resultBuffer.insert( 0 , 1 ); return
resultBuffer.toString(); } } |
leetcode--Add Binary,布布扣,bubuko.com
原文:http://www.cnblogs.com/averillzheng/p/3769098.html