[LeetCode]Multiply Strings

1422 단어 자바LeetCodeString
Given two numbers represented as strings, return multiplication of the numbers as a string.
Note: The numbers can be arbitrarily large and are non-negative.
311/311 test cases passed.
   Status: 
Accepted
Runtime: 
298 ms
public class Solution {
    public String multiply(String num1, String num2) {
        char []c1 = new StringBuilder(num1).reverse().toString().toCharArray();
        char []c2 = new StringBuilder(num2).reverse().toString().toCharArray();
        List<Integer> list = new ArrayList<>();
        for(int i=0;i<num1.length();i++){
        	for(int j=0;j<num2.length();j++){
        		int mul = (c1[i]-'0')*(c2[j]-'0');
        		while(list.size()<i+j+1){
        			list.add(0);
        		}
        		int cur = mul+list.get(i+j);
        		list.set(i+j, cur%10);
        		int pre = cur/10;
        		if(pre!=0){
        			while(list.size()<i+j+2){
        				list.add(0);
        			}
					list.set(i + j + 1, list.get(i+j+1)+pre);
        		}
        	}
        }
        StringBuilder sb = new StringBuilder();
        for(int i=list.size()-1;i>=0;i--){
        	sb.append(list.get(i));
        }
        while(sb.length()>0&&sb.charAt(0)=='0'){
        	sb.deleteCharAt(0);
        }
        if(sb.length()==0) return "0";
        return sb.toString();
    }
}

좋은 웹페이지 즐겨찾기