leetcode--Multiply Strings
2017-08-08 09:34
302 查看
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.
[java] view
plain copy
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();
}
}
原文链接http://blog.csdn.net/crazy__chen/article/details/45752001
Note: The numbers can be arbitrarily large and are non-negative.
[java] view
plain copy
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();
}
}
原文链接http://blog.csdn.net/crazy__chen/article/details/45752001
相关文章推荐
- LeetCode:Multiply Strings
- Leetcode Multiply Strings
- leetcode Multiply Strings
- leetcode-multiply strings
- leetcode 43: Multiply Strings
- LeetCode(43) Multiply Strings
- [leetcode] Multiply Strings
- leetcode(43)Multiply Strings
- ★leetcode43_Multiply Strings
- LeetCode---Multiply Strings
- Leetcode: Multiply Strings
- [LeetCode 43] Multiply Strings
- LeetCode 43 Multiply Strings
- LeetCode - Multiply Strings
- 【leetcode】【43】Multiply Strings
- leetcode Multiply Strings
- Multiply Strings leetcode java
- leetcode面试准备:Multiply Strings
- Multiply Strings ---leetcode
- [LeetCode][Java] Multiply Strings