标签:
Given two binary strings, return their sum (also a binary string).
a = 11
b = 1
Return 100
分析:
这个和10进制加法一样。
total = a + b + carryover;
digit = total % 2;
carryover = total / 2;
1 public class Solution { 2 /** 3 * @param a a number 4 * @param b a number 5 * @return the result 6 */ 7 public String addBinary(String a, String b) { 8 if (a == null || b == null) return null; 9 10 int aIndex = a.length() - 1; 11 int bIndex = b.length() - 1; 12 int carryover = 0; 13 int aValue = 0, bValue = 0; 14 StringBuilder sb = new StringBuilder(); 15 16 while(aIndex >= 0 || bIndex >= 0 || carryover != 0) { 17 if (aIndex >= 0) { 18 aValue = a.charAt(aIndex) - ‘0‘; 19 } else { 20 aValue = 0; 21 } 22 23 if (bIndex >= 0) { 24 bValue = b.charAt(bIndex) - ‘0‘; 25 } else { 26 bValue = 0; 27 } 28 29 int sum = aValue + bValue + carryover; 30 sb.insert(0, sum % 2); 31 carryover = sum / 2; 32 aIndex--; 33 bIndex--; 34 } 35 return sb.toString(); 36 } 37 }
标签:
原文地址:http://www.cnblogs.com/beiyeqingteng/p/5658951.html