您的位置:首页 > 其它

leetcode--Multiply Strings

2015-05-15 23:09 218 查看
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.public class Solution {
public String multiply(String num1, String num2) {
int[] res = new int[num1.length()+num2.length()];
for(int i=num1.length()-1;i>=0;i--){
for(int j=num2.length()-1;j>=0;j--){
int n1 = num1.charAt(i)-'0';
int n2 = num2.charAt(j)-'0';
res[i+j+1] += n1*n2;
}
}
int flag = 0;
for(int i=res.length-1;i>=0;i--){
int tmp = (res[i] + flag) % 10;
flag = (res[i] + flag) / 10;
res[i] = tmp;
}
StringBuilder sb = new StringBuilder();
for (int num : res) sb.append(num);
while (sb.length() != 0 && sb.charAt(0) == '0') sb.deleteCharAt(0);
return sb.length() == 0 ? "0" : sb.toString();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: