250x250
반응형
Notice
Recent Posts
Recent Comments
Link
N
(Leet Code c++)Add Binary 본문
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
반응형
'Leet Code 알고리즘' 카테고리의 다른 글
(Leet Code c++)Climbing Stairs (0) | 2021.07.12 |
---|---|
(Leet Code c++)Sqrt(x) (0) | 2021.07.09 |
(Leet Code c++)Plus One (0) | 2021.07.09 |
(Leet Code c++)Length of Last Word (0) | 2021.07.09 |
(Leet Code c++)Container With Most Water (0) | 2021.07.08 |