标签:style blog class code java c
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.
1 public String multiply(String num1, String num2) { 2 if(num1.equals("0")||num2.equals("0")){ 3 return "0"; 4 } 5 String re = ""; 6 for (int i = 0; i < num1.length(); i++) { 7 String temp = ""; 8 int in = 0; 9 for (int j = 0; j < num2.length(); j++) { 10 int k = (num2.charAt(num2.length() - 1 - j) - ‘0‘) 11 * (num1.charAt(num1.length() - 1 - i) - ‘0‘) + in; 12 temp = (k % 10) + temp; 13 in = k / 10; 14 } 15 if (in > 0) { 16 temp = in + temp; 17 } 18 if (i == 0) { 19 re = temp; 20 } else { 21 String t = ""; 22 int in2 = 0; 23 for (int m = 1; m <= i; m++) { 24 t = String.valueOf(re.charAt(re.length() - m)) + t; 25 } 26 for (int m = 0; m <= re.length() - 1 - i; m++) { 27 int k = (temp.charAt(temp.length() - 1 - m) - ‘0‘) 28 + (re.charAt(re.length() - 1 - i - m) - ‘0‘) + in2; 29 t = (k % 10) + t; 30 in2 = k / 10; 31 } 32 for (int m = 0; m < temp.length() + i - re.length(); m++) { 33 int k = (temp.charAt(temp.length() + i - re.length() - m 34 - 1) - ‘0‘) 35 + in2; 36 t = (k % 10) + t; 37 in2 = k / 10; 38 } 39 if (in2 > 0) { 40 t = in2 + t; 41 } 42 re = t; 43 } 44 // System.out.println(temp); 45 } 46 return re; 47 }
没啥可说的,去看BigInteger实现吧。。。
我自己写的耗时716ms,调用BigInteger耗时480ms。。
Multiply Strings,布布扣,bubuko.com
标签:style blog class code java c
原文地址:http://www.cnblogs.com/apoptoxin/p/3728804.html