问题描述
给定两个二进制字符串,要求求出它们的和。题目链接:**点我**
样例输入输出
输入:a = “11”, b = “1”
输出:”100”
输入:a = “1010”, b = “1011”
输出:”10101”
问题解法
此题类似大数相加,直接模拟加法求解过程即可。代码如下:
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 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
| class Solution { public String addBinary(String a, String b) { StringBuilder sb = new StringBuilder(); int i = a.length() - 1; int j = b.length() - 1; int carry = 0; while (i >= 0 && j >= 0) { int first = a.charAt(i) - '0'; int second = b.charAt(j) - '0'; int num = (carry + first + second) % 2; carry = (carry + first + second) / 2; sb.append(num); i--; j--; } while (i >= 0) { int temp = a.charAt(i) - '0'; int num = (carry + temp) % 2; carry = (carry + temp) / 2; sb.append(num); i--; }
while (j >= 0) { int temp = b.charAt(j) - '0'; int num = (carry + temp) % 2; carry = (carry + temp) / 2; sb.append(num); j--; } if (carry > 0) { sb.append(carry); } return sb.reverse().toString(); } }
|