67. Add Binary
问题描述:
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"
解题思路:
我原来的代码巨长无比(就是正常的思路)
想看看有没有人又简短的代码。
我就知道,一定有。
代码:
class Solution { public: string addBinary(string a, string b) { int len1 = a.size(); if(len1 == 0) return b; int len2 = b.size(); if(len2 == 0) return a; int c = 0, i = len1-1, j = len2-1; string s; while(c > 0 || i > -1 || j > -1){ c += i > -1 ? a[i--] - '0' : 0; c += j > -1 ? b[j--] - '0' : 0; s.push_back(char(c%2 + '0')); c = c/2; } reverse(s.begin(), s.end()); return s; } };