题目:
Given two binary strings, return their sum (also a binary string).
For example,
a ="11"
b = "1"
Return "100"
. 链接:
一刷,最简单的分两段计算。
class Solution(object): def addBinary(self, a, b): if not a: return b if not b: return a result = [] common_length = min(len(a), len(b)) carry = 0 for idx in range(1, common_length + 1): carry, ret = (int(a[-idx]) + int(b[-idx]) + carry) / 2, (int(a[-idx]) + int(b[-idx]) + carry) % 2 result.append(str(ret)) rest = a if len(a) > common_length else b for idx in range(common_length + 1, len(rest) + 1): carry, ret = (int(rest[-idx]) + carry) / 2, (int(rest[-idx]) + carry) % 2 result.append(str(ret)) if carry: result.append(str(carry)) result.reverse() return ''.join(result)
一次遍历,可以减少边界条件的分析
class Solution(object): def addBinary(self, a, b): if not a: return b if not b: return a result = [] a_index = len(a) - 1 b_index = len(b) - 1 carry = 0 while a_index >= 0 or b_index >= 0: a_val = int(a[a_index]) if a_index >= 0 else 0 b_val = int(b[b_index]) if b_index >= 0 else 0 carry, ret = (a_val + b_val + carry) / 2, (a_val + b_val + carry) % 2 result.append(str(ret)) a_index -= 1 b_index -= 1 if carry: result.append(str(carry)) result.reverse() return ''.join(result)
2/12/2017, Java, 无脑乱刷。非常需要改进
错误
1. StringBuilder的各种方法:setLength(), setCharAt(), append()
2. 判断第一次相加是否为0,初始条件判断缺失,不但在2个相加时,最后只剩下一个String的时候第一次也需要判断
3. char没有int(char)这种方法,只能通过char - '0'来判断
1 public class Solution { 2 public String addBinary(String a, String b) { 3 StringBuilder ret = new StringBuilder(); 4 ret.setLength(Math.max(a.length(), b.length())); 5 int sum; 6 int carry = 0; 7 int i = a.length() - 1, j = b.length() - 1; 8 9 for(;i >= 0 && j >= 0;i--, j--) {10 sum = a.charAt(i) - '0' + b.charAt(j) - '0' + carry;11 if (sum == 0) {12 ret.setCharAt(Math.max(i, j), '0');13 carry = 0;14 } else if (sum == 1) {15 ret.setCharAt(Math.max(i, j), '1');16 carry = 0;17 } else if (sum == 2) {18 ret.setCharAt(Math.max(i, j), '0');19 carry = 1;20 } else {21 ret.setCharAt(Math.max(i, j), '1');22 carry = 1;23 }24 }25 for(; i >= 0; i--) {26 sum = a.charAt(i) - '0' + carry;27 if (sum == 0) {28 ret.setCharAt(i, '0');29 carry = 0;30 } else if (sum == 1) {31 ret.setCharAt(i, '1');32 carry = 0;33 } else {34 ret.setCharAt(i, '0');35 carry = 1; 36 }37 }38 for(; j >= 0; j--) {39 sum = b.charAt(j) - '0' + carry;40 if (sum == 0) {41 ret.setCharAt(j, '0');42 carry = 0;43 } else if (sum == 1) {44 ret.setCharAt(j, '1');45 carry = 0;46 } else {47 ret.setCharAt(j, '0');48 carry = 1; 49 }50 } 51 if (carry != 0) {52 StringBuilder ret1 = new StringBuilder("1");53 ret1.append(ret);54 return ret1.toString();55 }56 return ret.toString();57 }58 }