[LeetCode] 415. Add Strings
문제 출처: https://leetcode.com/problems/add-strings/
Add Strings - 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
문제
음수가 아닌 두 정수 num1과 num2가 문자열의 형태로 주어지면, num1과 nums2의 합을 문자열 형태로 반환하라.
(BigInteger 같은) 큰 정수를 다루는 내장 라이브러리의 사용 없이 문제를 풀어야 한다. 또한 입력으로 주어지는 값을 직접적으로 정수로 변형해서는 안된다.
예제
Input: num1 = "11", num2 = "123"
Output: "134"
Input: num1 = "11", num2 = "123"
Output: "134"
Input: num1 = "0", num2 = "0"
Output: "0"
풀이
입력으로 주어지는 두 정수 문자열을 대상으로 실제 사람이 덧셈을 하는 과정을 코드로 작성하는 문제이다.
사람이 덧셈을 하는 과정을 생각해보자. 123 + 11은 아래와 같이 표현할 수 있다.
1 | 2 | 3 | |
+ | 1 | 1 | |
----- | ----- | ----- | ----- |
= | 1 | 3 | 4 |
사람은 덧셈을 하기 위해서 일의 자리는 일의 자리끼리, 십의 자리는 십의 자리 끼리 열을 맞춰 세운 후, 해당 값을 차례차례 더하는 방식을 취한다. 만약 자리 수의 계산 결과가 10 이상의 값을 갖는 다면 아래와 같이 계산한다.
carry | 1 | ||
1 | 2 | 3 | |
+ | 1 | 8 | |
----- | ----- | ----- | ----- |
= | 1 | 4 | 1 |
이와 같이 일의 자리부터 시작하여 각 자리 수에 해당하는 값을 가져와 더하고, 그 결과에 따라 answer에 문자열을 추가하는 방식을 취하면 내장 라이브러리 없이도 큰 수를 더할 수 있다.
var addStrings = function(num1, num2) {
const num1Str = num1.split('').map(char => char.charCodeAt(0) - 48);
const num2Str = num2.split('').map(char => char.charCodeAt(0) - 48);
let answer = '';
let carry = 0;
while (num1Str.length || num2Str.length) {
const n1Digit = num1Str.length ? num1Str.pop() : 0;
const n2Digit = num2Str.length ? num2Str.pop() : 0;
const digitSum = carry + n1Digit + n2Digit;
carry = digitSum > 9 ? 1 : 0;
answer = (digitSum % 10) + answer;
}
if (carry) { answer = carry + answer; }
return answer;
};
Github: 415.js
GitHub - opwe37/Algorithm-Study
Contribute to opwe37/Algorithm-Study development by creating an account on GitHub.
github.com