본문 바로가기
LeetCode

[LeetCode] 43. Multiply Strings

by JungSeung 2023. 11. 8.
728x90

https://leetcode.com/

Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2, also represented as a string.

 

Note: You must not use any built-in BigInteger library or convert the inputs to integer directly.

 

Example 1:

Input:  num1 = "2", num2 = "3"
Output: "6"

 

Example 2:

Input: num1 = "123", num2 = "456"
Output: "56088"

 

Constraints:

  • 1 <= num1.length, num2.lenght <= 200
  • num1 and num2 consist of digits only.
  • Both num1 and num2 do not contain any leading zero, except the number 0 itself.

 

Code :

var multiply = function(num1, num2) {
    // 두 숫자의 길이를 변수에 저장합니다.
    const m = num1.length, n = num2.length;
    // 결과를 저장할 배열을 생성하고 0으로 초기화합니다.
    const pos = new Array(m + n).fill(0);
    
    // 첫 번째 숫자를 거꾸로 순회합니다.
    for (let i = m - 1; i >= 0; i--) {
        // 두 번째 숫자를 거꾸로 순회합니다.
        for (let j = n - 1; j >= 0; j--) {
            // 두 숫자의 각 자릿수를 곱하고 현재 자릿수와 다음 자릿수를 계산합니다.
            const mul = (num1.charCodeAt(i) - '0'.charCodeAt(0)) * (num2.charCodeAt(j) - '0'.charCodeAt(0));
            const p1 = i + j, p2 = i + j + 1;
            const sum = mul + pos[p2];
            
            // 각 자릿수에 곱셈 결과를 더합니다.
            pos[p1] += Math.floor(sum / 10);
            pos[p2] = sum % 10;
        }
    }
    
    // 결과를 저장할 문자열을 초기화합니다.
    let result = "";
    // pos 배열의 각 요소를 문자열로 결합합니다.
    for (let p of pos) {
        // 결과가 0으로 시작하지 않도록 첫 자리가 0이면 건너뜁니다.
        if (!(result.length === 0 && p === 0)) {
            result += p;
        }
    }
    // 결과가 0이라면 "0"을 반환하고, 그렇지 않으면 결과를 반환합니다.
    return result.length === 0 ? "0" : result;
};

 

Solutions Code :

var multiply = function(num1, num2) {
    // 두 숫자 중 하나라도 '0'이라면 곱은 0이므로 '0'을 반환합니다.
    if (num1 === '0' || num2 === '0') return '0'
    
    // 두 숫자의 길이를 저장하고 결과를 저장할 배열을 초기화합니다.
    const m = num1.length, n = num2.length, res = new Array(m+n).fill(0)
    
    // 첫 번째 숫자를 거꾸로 순회합니다.
    for (let i=m-1; i>=0; i--) {
        // 두 번째 숫자를 거꾸로 순회합니다.
        for (let j=n-1; j>=0; j--) {
            // 각 자릿수에 해당하는 인덱스를 계산합니다.
            const p1=i+j, p2=i+j+1
            // 현재 결과를 저장하고, 각 자릿수에 올림수를 더합니다.
            let sum = res[p2] + Number(num1[i]) * Number(num2[j])
            res[p2] = sum%10
            res[p1] += Math.floor(sum/10)
        }
    }
    // 결과 배열의 첫 번째 값이 0이라면 제거합니다.
    if (res[0] === 0) res.shift()
    // 결과 배열을 문자열로 결합하여 반환합니다.
    return res.join('')
};

 

 

출처 : 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] 45. Jump Game II  (2) 2023.11.09
[LeetCode] 44. Wildcard Matching  (0) 2023.11.09
[LeetCode] 42. Trapping Rain Water  (0) 2023.11.07
[LeetCode] 41. First Missing Positive  (0) 2023.11.07
[LeetCode] 40. Combination Sum II  (0) 2023.11.06