标签:
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 if (a == null) { 4 return b; 5 } 6 if (b == null) { 7 return a; 8 } 9 if (a.length() < b.length()) { 10 String temp = a; 11 a = b; 12 b = temp; 13 } 14 int indexA = a.length() - 1; 15 int indexB = b.length() - 1; 16 int carry = 0; 17 String result = ""; 18 while (indexB >= 0) { 19 int sum = (int)a.charAt(indexA) - ‘0‘ + (int)b.charAt(indexB) - ‘0‘ + carry; 20 result = String.valueOf(sum % 2) + result; 21 carry = sum / 2; 22 --indexA; 23 --indexB; 24 } 25 while (indexA >= 0) { 26 int sum = (int)a.charAt(indexA) - ‘0‘ + carry; 27 result = String.valueOf(sum % 2) + result; 28 carry = sum / 2; 29 --indexA; 30 } 31 if (carry == 1) { 32 result = "1" + result; 33 } 34 return result; 35 } 36 }
Similar Problem : LeetCode 2. Add Two Numbers
标签:
原文地址:http://www.cnblogs.com/FLAGyuri/p/5495276.html