728x90
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 <= 10^4
- a and b consist only of '0' or '1' characters.
- Each string does not contain leading zeros except for the zero itself.
Solutions Code :
function addBinary(a, b) {
let result = '';
let carry = 0;
let i = a.length - 1;
let j = b.length - 1;
// 두 문자열 중 한 쪽이라도 다 탐색할 때까지 진행
while (i >= 0 || j >= 0) {
let sum = carry;
if (i >= 0) sum += parseInt(a[i--]);
if (j >= 0) sum += parseInt(b[j--]);
// sum이 2보다 작으면 sum을 결과에 추가하고 carry는 0
// sum이 2라면 0을 결과에 추가하고 carry는 1
// sum이 3이라면 1을 결과에 추가하고 carry는 1
result = (sum % 2) + result;
carry = sum >= 2 ? 1 : 0;
}
// 마지막으로 carry가 1인 경우 1을 결과에 추가해줌
if (carry) result = '1' + result;
return result;
}
출처 : https://leetcode.com/problemset/all/
Problems - LeetCode
Boost your coding interview skills and confidence by practicing real interview questions with LeetCode. Our platform offers a range of essential problems for practice, as well as the latest questions being asked by top-tier companies.
leetcode.com
728x90
'LeetCode' 카테고리의 다른 글
[LeetCode] 69. Sqrt(x) (0) | 2024.02.23 |
---|---|
[LeetCode] 68. Text Justification (0) | 2024.02.19 |
[LeetCode] 66. Plus One (2) | 2024.01.29 |
[LeetCode] 65. Valid Number (2) | 2024.01.23 |
[LeetCode] 64. Minimum Path Sum (0) | 2024.01.14 |