Leet Code 알고리즘
(Leet Code c++)Add Binary
naeunchan
2021. 7. 9. 10:31
728x90
반응형
67. Add Binary
Given two binary strings a and b, return their sum as a binary string.
Example 1:
Input: a = "11", b = "1" Output: "100"
Example 2:
Input: a = "1010", b = "1011" Output: "10101"
Constraints:
- 1 <= a.length, b.length <= 104
- a and b consist only of '0' or '1' characters.
- Each string does not contain leading zeros except for the zero itself.
class Solution {
public:
string addBinary(string a, string b) {
string answer = "";
int aIndex = a.size() - 1;
int bIndex = b.size() - 1;
int carry = 0;
while((aIndex != -1 || bIndex != -1) || carry){
if(aIndex >= 0){
carry += a[aIndex--] == '1' ? 1 : 0;
}
if(bIndex >= 0){
carry += b[bIndex--] == '1' ? 1 : 0;
}
answer = to_string(carry % 2) + answer;
carry /= 2;
}
return answer;
}
};
728x90
반응형