伴你如风、护你如影|

xzh-yyds

园龄:3年9个月粉丝:0关注:2

leetcode43-字符串相乘

字符串相乘

  • 逐位相乘
class Solution {
    public String multiply(String num1, String num2) {
        if(num1.equals("0") || num2.equals("0"))    return "0";
        int m = num1.length(), n = num2.length();
        int arr[] = new int[m+n];
        for(int i = m-1; i >= 0; i--){
            int x = num1.charAt(i)-'0';
            for(int j = n-1; j >= 0; j--){
                int y = num2.charAt(j)-'0';
                arr[i+j+1] += x*y;
            }
        }
        for(int i = m+n-1; i > 0; i--){
            arr[i-1] += arr[i] / 10;
            arr[i] %= 10;
        }
        int index = arr[0] == 0 ? 1 : 0;
        StringBuilder sb = new StringBuilder();
        while(index < m+n){
            sb.append(arr[index]);
            index++;
        }
        return sb.toString();
    }
}

本文作者:xzh-yyds

本文链接:https://www.cnblogs.com/xzh-yyds/p/16614263.html

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

posted @   xzh-yyds  阅读(15)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示
评论
收藏
关注
推荐
深色
回顶
展开