Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 |
Tags
- MemoryBarrier
- JavaScript
- 백준
- 제로베이스
- 완전탐색
- 문자열&연산자
- React
- leetcode
- c#
- 코딩테스트 스터디
- N과 M(2)
- 알고리즘
- C++
- 자바스크립트
- Server
- 메모리 배리어
- socket
- 코딩테스트
- map
- BFS
- dfs
- 제로베이스 프론트엔드 스쿨
- 프로그래머스
- 서버
- 구조체
- 프론트엔드 스쿨
- 멀티스레드
- Algorithm
- 백트래킹
- 구현
Archives
- Today
- Total
Written
leetcode / 67. Add Binary / JavaScript 본문
https://leetcode.com/problems/add-binary/
Add Binary - LeetCode
Can you solve this real interview question? 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: *
leetcode.com
a와 b로 주어지는 두 이진수의 덧셈을 다시 이진수로 출력하는 문제입니다.
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.
이 문제 역시 66번 문제와 비슷하게 입력으로 주어지는 값이 매우 큰 케이스가 있습니다.
단순히 a와 b를 십진수로 변환해서 더한 후 그 수를 다시 이진수로 변환하여 제출하면 틀리는 케이스가 존재합니다.
a.length가 10000까지 가능합니다. 그렇기 때문에 BigInt를 통해서 십진수로 변경하고, 두 수를 더한 후
다시 이진수로 변경하면 답을 구할 수 있습니다. BigInt() 괄호 안에 이진수의 형태로 문자열을 입력하면 BigInt형으로
십진수를 반환해줍니다. (EX => BigInt(0b1110101) // 117n반환)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
/**
* @param {string} a
* @param {string} b
* @return {string}
*/
var addBinary = function(a, b) {
let aToInt = BigInt(`0b${a}`);
let bToInt = BigInt(`0b${b}`);
let temp = aToInt + bToInt;
let answer = temp.toString(2);
return answer;
};
|
cs |
'알고리즘 문제풀이' 카테고리의 다른 글
leetcode / Unique Binary Search Tree II / JavaScript (0) | 2023.02.26 |
---|---|
leetcode / 7. Reverse Integer / JavaScript (0) | 2023.02.21 |
leetcode / 66. Plus One / JavaScript (0) | 2023.02.21 |
스터디 4주차 / leetcode / Longest Palindromic Substring / JavaScript (0) | 2023.02.01 |
스터디 4주차 / leetcode / Remove Element / JavaScript (2) | 2023.02.01 |