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();
}
}
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();
}
}
相关文章推荐
- leetcode_Multiply Strings
- LeetCode43_Multiply Strings
- LeetCode Multiply Strings
- Leetcode之Multiply Strings
- LeetCode 43: Multiply Strings
- Leetcode 43. Multiply StringsI
- [LeetCode] Multiply Strings 字符串相乘
- [LeetCode] Multiply Strings
- [leetcode] Multiply Strings
- LeetCode-Multiply Strings-字符串乘法-大整数-字符串操作
- LeetCode: Multiply Strings [042]
- Multiply Strings ---leetcode
- leetcode做题总结,题目Multiply Strings 43
- [leetcode javascript解题]Multiply Strings
- LeetCode:Multiply Strings
- 【leetcode】Multiply Strings
- LeetCode 43 - Multiply Strings
- LeetCode Multiply Strings
- leetcode----Multiply Strings
- [LeetCode] Multiply Strings