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.
将num1与0-9相乘的结果存到数组里面去,然后根据num2中的每一位,从数组中获取结果,注意添加0.public String sum(String num1, String num2) { int lenOne = num1.length(); int lenTwo = num2.length(); int i = lenOne - 1; int j = lenTwo - 1; int flag = 0; StringBuilder builder = new StringBuilder(); while(i >= 0 && j >= 0) { int one = Integer.parseInt(num1.charAt(i) + ""); int two = Integer.parseInt(num2.charAt(j) + ""); int temp = one + two + flag; flag = temp / 10; builder.append(temp % 10); i--; j--; } while (i >= 0) { int one = Integer.parseInt(num1.charAt(i) + ""); int temp = one + flag; flag = temp / 10; builder.append(temp % 10); i--; } while (j >= 0) { int two = Integer.parseInt(num2.charAt(j) + ""); int temp = two + flag; flag = temp / 10; builder.append(temp % 10); j--; } if (flag != 0) { builder.append(flag); } return builder.reverse().toString(); } public String multiply(String num1, String num2) { if (num1 == null || num2 == null || num1.equals("") || num2.equals("")) { return null; } String[] pro = new String[10]; int lenOne = num1.length(); pro[0] = "0"; pro[1] = num1; for (int k = 2; k < 10; k++) { int flag = 0; StringBuilder builder = new StringBuilder(); for (int i = lenOne; i > 0; i--) { int temp = Integer.parseInt(num1.charAt(i - 1) + ""); int acc = temp * k + flag; flag = acc / 10; builder.append(acc % 10); } if (flag != 0) { builder.append(flag); } pro[k] = builder.reverse().toString(); } // System.out.println(); // for (int i = 0; i < 10; i++) { // System.out.println(pro[i]); // } // System.out.println(); int lenTwo = num2.length(); String product = "0"; for (int i = 0; i < lenTwo; i++) { int digit = Integer.parseInt(num2.charAt(i) + ""); String temp = pro[digit]; if (!temp.equals(pro[0])) { for (int j = 0; j < lenTwo - 1 - i; j++) { temp +="0"; } } product = sum(product, temp); } return product; }
Multiply Strings,布布扣,bubuko.com
原文地址:http://blog.csdn.net/u010378705/article/details/30245871