LeetCode: Multiply Strings. Java

2019-04-14 20:29发布

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 n = num2.length(); String[] addS = new String[n]; for(int i = 0; i < n; i++){ addS[i] = multiplyChar(num1, num2.charAt(i), n-1-i); } String res = sum(addS); int p = 0; while(p < res.length() && res.charAt(p) == '0') p++; if(p == res.length()) return "0"; else return res.substring(p); } public String multiplyChar(String num, char c, int digits){ int n = num.length(); char[] res = new char[n + 1]; int add = 0; for(int i = n; i >= 0; i--){ int b = 0; if(i-1 >= 0) b = num.charAt(i-1)-'0'; int cur = b*(c-'0')+add; add = cur / 10; cur %= 10; res[i] = (char)(cur+'0'); } int p = 0; while(p <= n && res[p] == '0') p++; if(p == n + 1) return "0"; else{ StringBuffer sb = new StringBuffer(); for(int i = 0; i < digits; i++){ sb.append('0'); } return new String(res, p, n-p+1) + sb.toString(); } } public String sum(String[] s){ StringBuffer res= new StringBuffer(); int p = 0; int cur = 0; int add = 0; int maxLength = 0; for(int i = 0; i < s.length; i++){ maxLength = Math.max(maxLength, s[i].length()); } do{ cur = 0; for(int i = 0; i < s.length; i++){ if(p < s[i].length()) cur += s[i].charAt(s[i].length()-1-p)-'0'; } cur += add; res.append(cur%10); add = cur / 10; p++; } while(cur != 0 || p < maxLength); return new String(res.reverse()); } }

版权声明:本文博客原创文章,博客,未经同意,不得转载。