Given two binary strings, return their sum (also a binary string).
For example,
a =
b =
Return
a =
"11"
b =
"1"
Return
"100"
.
从低位开始相加, 每得出一位的结果添加到result里 最后得到的result是低位在前边 所以要reverse一下.
只遍历了一次 时间复杂度是O(max(m,n)) 空间复杂度也是O(max(m,n))
public class Solution { public String addBinary(String a, String b) { if (a == null || a.length() == 0) { return b; } if (b == null || b.length() == 0) { return a; } int next = 0; int digit; StringBuilder res = new StringBuilder(); int i = a.length() - 1; int j = b.length() - 1; while (i >= 0 && j>=0) { digit = a.charAt(i) - '0' + b.charAt(j) - '0' + next; next = digit / 2; digit = digit % 2; res.append(digit); i--; j--; } while (i >= 0) { digit = a.charAt(i) - '0' + next; next = digit / 2; digit = digit % 2; res.append(digit); i--; } while (j >= 0) { digit = b.charAt(j) - '0' + next; next = digit / 2; digit = digit % 2; res.append(digit); j--; } if (next > 0) { res.append(next); } return res.reverse().toString(); } }
没有评论:
发表评论