Difficulty: Easy
Given two binary strings, return their sum (also a binary string).
The input strings are both non-empty and contains only characters 1
or 0
.
Example 1:
1 2
| Input: a = "11", b = "1" Output: "100"
|
Example 2:
1 2
| Input: a = "1010", b = "1011" Output: "10101"
|
Solution
Language: Java
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
| class Solution { public String addBinary(String a, String b) { if (a == null || b == null) { return ""; } if (a.length() == 0) { return b; } if (b.length() == 0) { return a; } int i = a.length() - 1; int j = b.length() - 1; StringBuilder sb = new StringBuilder(); int carry = 0; int cur = 0; while (i >= 0 || j >= 0) { cur = (i < 0 ? 0 : (a.charAt(i--) - '0')) + (j < 0 ? 0 : (b.charAt(j--) - '0')) + carry; sb.append(cur % 2); carry = cur / 2; } if (carry > 0) { sb.append(1); } sb.reverse(); return sb.toString(); } }
|