leetcode--Multiply Strings

来源:互联网 发布:手机淘宝新手怎么拿货 编辑:程序博客网 时间:2024/06/05 09:15

做这题的时候脑子有点迷糊,代码写的有点拖沓。题目不复杂,反正就是将string转成数组之后利用大数相乘的思想吧,注意一下最后返回的string里面字符的顺序问题就行了,还有一点,相乘之后得到的数组要找到不为零的最高索引(我用index表示)。

public class Solution {    public String multiply(String num1, String num2) {        int len_1 = num1.length();        int len_2 = num2.length();        int[] a = new int[len_1];        int[] b = new int[len_2];        for(int i=0; i<len_1; i++){            a[i] = num1.charAt(len_1-i-1)-'0';                       }        for(int i=0; i<len_2; i++){            b[i] = num2.charAt(len_2-i-1)-'0';        }        int[] c = new int[len_1+len_2];        int temp = 0;        for(int i=0; i<len_1; i++){            for(int j=0; j<len_2; j++){                c[i+j] += a[i]*b[j];            }        }        String res = "";        for(int i=0; i<len_1+len_2-1; i++){            c[i+1] += c[i]/10;            c[i] = c[i]%10;        }        int index;        for(index=c.length-1; index>=0;){            if(c[index]>0)break;            index--;        }        if(index>=0){            for(int i=0; i<=index; i++){                res = (char)(c[i]+'0')+res;            }            return res;        }        return res+'0';    }}
1 0
原创粉丝点击