首页 > 代码库 > Multiply Strings
Multiply Strings
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。。
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。