0. 문제
https://leetcode.com/problems/add-binary/
Add Binary - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
두 개의 이진 문자열 a 및 b가 주어지면 그 합계를 이진 문자열로 반환합니다 .
#1
Input: a = "11", b = "1"
Output: "100"
#2
Input: a = "1010", b = "1011"
Output: "10101"
1.언어
자바스크립트(JavaScript)
2. 문제 풀이
var addBinary = function(a, b) {
var result = String(),
value = 0;
a = '0'.repeat(b.length - a.length > 0 ? b.length - a.length : 0) + a;
b = '0'.repeat(a.length - b.length > 0 ? a.length - b.length : 0) + b;
for (let i = a.length-1; i >= 0; i--){
value = Number(a[i]) + Number(b[i]) + value
if (value > 1){
value -= 2;
result = String(value) + result;
value = 1;
} else {
result = String(value) + result;
value = 0;
}
}
if (value) result = '1' + result;
return result
};
Runtime: 97 ms, faster than 51.97% of JavaScript online submissions for Add Binary.
Memory Usage: 44.1 MB, less than 33.81% of JavaScript online submissions for Add Binary.
이진수 덧셈이라 쉽게 풀었던 문제
각 String이 길이가 다를 수 있으므로 빈 수만큼 0을 붙히고 반복문으로 해결했다.
'LeetCode > 코딩 테스트 스터디 3주차' 카테고리의 다른 글
[LeetCode] 88. Merge Sorted Array 풀이 (JS) (0) | 2022.07.24 |
---|---|
[LeetCode] 12. Integer to Roman 풀이 (JS) (0) | 2022.07.24 |
[LeetCode] 83. Remove Duplicates from Sorted List 풀이 (JS) (0) | 2022.07.24 |
[LeetCode] 70. Climbing Stairs 풀이 (JS) (0) | 2022.07.24 |
[LeetCode] 69. Sqrt(x) 풀이 (JS) (0) | 2022.07.24 |