标签:style blog color os io ar for div 代码
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.
大整数的字符串乘法,我本来对字符串表示的大整数就不是太熟悉,至于溢出该怎么处理也是不大清楚,所以参考了别人的做法,然后自己凭着印象重做了一次
这里面的方法比较巧妙,也比较典型,需要掌握。还有需要注意溢出处理,这里的处理是:如果最高位产生进位carry,那么直接忽略这个carry
1 public class Solution { 2 public String multiply(String num1, String num2) { 3 num1 = new StringBuffer(num1).reverse().toString(); 4 num2 = new StringBuffer(num2).reverse().toString(); 5 int[] n1 = new int[num1.length()]; 6 int[] n2 = new int[num2.length()]; 7 int[] temp = new int[num1.length() + num2.length()]; 8 for (int i = 0; i < num1.length(); i++) { 9 n1[i] = (int)(num1.charAt(i) - ‘0‘); 10 for (int j = 0; j < num2.length(); j++) { 11 n2[j] = (int)(num2.charAt(j) - ‘0‘); 12 temp[i + j] += n1[i] * n2[j]; 13 } 14 } 15 16 StringBuffer sb = new StringBuffer(); 17 int digit = 0; 18 int carry = 0; 19 for (int k = 0; k < temp.length; k++) { 20 digit = temp[k] % 10; 21 carry = temp[k] / 10; 22 sb.insert(0, digit); 23 if (k < temp.length - 1) { 24 temp[k + 1] += carry; 25 } 26 } 27 28 while (sb.length() > 0 && sb.charAt(0) == ‘0‘) { 29 sb.deleteCharAt(0); 30 } 31 return sb.length() == 0? "0" : sb.toString(); 32 } 33 }
标签:style blog color os io ar for div 代码
原文地址:http://www.cnblogs.com/EdwardLiu/p/3957599.html