标签:
Given two numbers represented as strings, return multiplication of the numbers as a string.
Note:
分析:
把结果放在一个数组里,用startIndex来移动起始位置。
1 public class Solution { 2 public String multiply(String num1, String num2) { 3 if (num1 == null || num1.length() == 0 || num2 == null || num2.length() == 0) return ""; 4 int[] result = new int[num1.length() + num2.length()]; 5 6 int startIndex = 0; 7 for (int i = num1.length() - 1; i >= 0; i--) { 8 int number1 = num1.charAt(i) - ‘0‘; 9 int extra = 0; 10 for (int j = num2.length() - 1; j >= 0; j--) { 11 int number2 = num2.charAt(j) - ‘0‘; 12 int value = number1 * number2 + result[(result.length - 1) - startIndex + j - (num2.length() - 1)] + extra; 13 extra = value / 10; 14 value = value % 10; 15 result[(result.length - 1) - startIndex + j - (num2.length() - 1)] = value; 16 } 17 result[(result.length - 1) - startIndex - 1 - (num2.length() - 1)] = extra; 18 startIndex++; 19 } 20 String str = ""; 21 boolean isBeginningZero = true; 22 for (int i = 0; i < result.length; i++) { 23 if (!(result[i] == 0 && isBeginningZero == true)) { 24 isBeginningZero = false; 25 str += result[i]; 26 } 27 } 28 return str == "" ? "0" : str; 29 } 30 }
标签:
原文地址:http://www.cnblogs.com/beiyeqingteng/p/5727811.html