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:
Input: a = "11", b = "1" Output: "100"
Example 2:
Input: a = "1010", b = "1011" Output: "10101"
Solution: Big integer
Similar to https://zxi.mytechroad.com/blog/math/leetcode-66-plus-one/
Time complexity: O(n)
Space complexity: O(n)
C++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
// Author: Huahua class Solution { public: string addBinary(string a, string b) { int carry = 0; int i = a.length() - 1; int j = b.length() - 1; string ans; while (i >= 0 || j >= 0) { int s = (i >= 0 ? a[i--] - '0' : 0) + (j >= 0 ? b[j--] - '0' : 0) + carry; carry = s >> 1; ans += '0' + (s & 1); } if (carry) ans += '1'; return {rbegin(ans), rend(ans)}; } }; |
请尊重作者的劳动成果,转载请注明出处!花花保留对文章/视频的所有权利。
如果您喜欢这篇文章/视频,欢迎您捐赠花花。
If you like my articles / videos, donations are welcome.
Be First to Comment