LeetCode: Multiply Strings. Java
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 {// simulate the manually calculated multiplication 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 ());}}