티스토리 뷰

 

leetcode.com/problems/multiply-strings/

 

Multiply 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

 

구현물로 Medium정도의 난이도이다

문자열 길이가 최대 109라 Number 형태의 곱셈이 아닌 각 자리수의 곱을 계산해야 한다.

 

import java.util.Arrays;

public class MultiplyString {
    public static void main(String[] args) {
        System.out.println(multiply("5", "12"));
    }
    public static String multiply(String num1, String num2) {
        if (isZero(num1) || isZero(num2)) return "0";

        int[] res = new int[220];
        for(int i =  num1.length() - 1, x=0; i >= 0; i--, x++) {
            int n1 = convertCharToInteger(num1.charAt(i));
            for(int j = num2.length() - 1, y=0; j >= 0; j--, y++) {
                int n2 = convertCharToInteger(num2.charAt(j));
                res[x+y] += n1 * n2;
            }
        }

        StringBuilder sb = new StringBuilder();
        for(int i = 0; i < num1.length() + num2.length(); i++) {
            if (res[i] >= 10) {
                res[i+1] += res[i] / 10;
                res[i] = res[i] % 10;
            }
            sb.insert(0, res[i]);
        }
        if(sb.charAt(0) == '0') sb.deleteCharAt(0);
        return sb.toString();
    }

    private static int convertCharToInteger(char c) {
        return c - 48;
    }
    private static boolean isZero(String num) {
        return num.length()==1 && num.charAt(0) == '0';
    }
}
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
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 31
글 보관함