leetcode:문자열 곱 하기(java)

package LeetCode;

import java.util.ArrayList;
import java.util.List;

public class Multiply {
    /*
         :                 n*n                                  
               i+j
     */
     public String multiply(String num1, String num2) {
        StringBuilder res = new StringBuilder();
        char[] a = num1.toCharArray();
        char[] b = num2.toCharArray();
        if ((num1.length()==1&&num1.equals("0"))||(num2.length()==1&&num2.equals("0")))return "0";
        //                 
        int[] result = new int[a.length + b.length];
        //      
        for (int i = a.length-1; i >=0; i--) {
            for (int j=b.length-1; j >=0;  j--) {
                result[a.length-1-i + b.length-1-j]+= (a[i] - 48) * (b[j] - 48);
            }
        }
        for (int i = 0; i < result.length - 1; i++) {
            if (result[i] >= 10) {
                result[i + 1] += result[i] / 10;
                result[i] = result[i] % 10;
            }
        }
        //                       
        boolean juge = false;
        for (int i = result.length - 1; i >= 0; i--) {
            if (result[i] != 0) {
                juge = true;
            }
            if (juge) {
                res.append(result[i]);
            }
        }
        return res.toString();
    }

    public static void main(String[] args) {
        Multiply a = new Multiply();
        System.out.println(a.multiply("0",
                "0"));
    }
}

좋은 웹페이지 즐겨찾기