1. 程式人生 > >[LeetCode 43]Multiply Strings

[LeetCode 43]Multiply Strings

break product eve integer while build 保存 養成 []

記錄加入Datawhale第四天(中間出去了三天沒有按時正是罪過呀),養成每天做題的好習慣

題目描述:

  Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2, also represented as a string.

題目要求不能使用庫函數直接轉換為整數,因此想到的是將結果保存到一個數組中在轉化為字符串

Java代碼:

 1 class Solution {
 2    public String multiply(String num1, String num2) {
3 int[] ret = new int[num1.length() + num2.length()]; 4 int n = ret.length - 1; 5 for (int i = num2.length() - 1; i >= 0; i--) { 6 char c1 = num2.charAt(i); 7 int index = n; 8 for (int j = num1.length() - 1; j >= 0; j--) { 9
char c2 = num1.charAt(j); 10 int tmp = (c1 - ‘0‘) * (c2 - ‘0‘); 11 ret[index] += tmp % 10; 12 ret[index - 1] += tmp / 10; 13 index--; 14 } 15 n--; 16 } 17 StringBuilder str = new
StringBuilder(); 18 int i = ret.length - 1; 19 for (; i > 0; i--) { 20 int tmp = ret[i]; 21 ret[i] = tmp % 10; 22 ret[i - 1] += tmp / 10; 23 str.append(ret[i]); 24 } 25 if(ret[i] > 0) str.append(ret[i]); 26 str.reverse(); 27 int start = 0; 28 while(str.charAt(start) == ‘0‘ && start < str.length()-1){//去除前面的0 29 if(str.charAt(start) != ‘0‘) break; 30 str.deleteCharAt(start); 31 } 32 return str.toString(); 33 } 34 }

[LeetCode 43]Multiply Strings