1. 程式人生 > >Leetcode演算法Java全解答--43. 字串相乘

Leetcode演算法Java全解答--43. 字串相乘

Leetcode演算法Java全解答–43. 字串相乘

文章目錄

題目

給定兩個以字串形式表示的非負整數 num1 和 num2,返回 num1 和 num2 的乘積,它們的乘積也表示為字串形式。

示例:


示例 1:

輸入: num1 = "2", num2 = "3"
輸出: "6"
示例 2:

輸入: num1 = "123", num2 = "456"
輸出: "56088"
說明:

num1 和 num2 的長度小於110。
num1 和 num2 只包含數字 0-9。
num1 和 num2 均不以零開頭,除非是數字 0 本身。
不能使用任何標準庫的大數型別(比如 BigInteger)或直接將輸入轉換為整數來處理。

想法

// TODO

結果

// TODO

總結

// TODO

程式碼

我的答案

    public String multiply(String num1, String num2) {
       if("0".equals(num1) || "0".equals(num2)) return "0";
 
        int len1 = num1.length(), len2 = num2.length();
        int A[] = new int[len1 + len2];
        for(int i = len1-1; i >= 0; i--){
            for(int j = len2-1; j >= 0; j--){
                A[len1+len2-2-i-j] += (num1.charAt(i) - '0') * (num2.charAt(j) - '0');
            }
        }
 
        String result = "";
        for(int i = 0; i < len1+len2-1; i++){
            A[i+1] += A[i]/10;
            A[i] %= 10;
            result = (char)(A[i] + '0') + result;
        }
        result = (0 == A[len1+len2-1] ? "" : (char)(A[len1+len2-1]+'0')) + result;
 
        return result;
    }
  

大佬們的答案

 public String multiply(String num1, String num2) {
		if(num1.isEmpty() || num2.isEmpty() 
           ||(num1.length() == 1 && num1.charAt(0) == '0') 
           || (num2.length() == 1 && num2.charAt(0) == '0'))
			return "0";
		int len1 = num1.length();
		int len2 = num2.length();
		int[] ans = new int[len1 + len2 + 1];
		for(int i = 0 ; i < len1;i++) {
			int a = num1.charAt(i) - '0';
			for(int j = 0; j < len2; j++) {
				int b = num2.charAt(j) - '0';
				ans[len1 + len2 - i - j - 2] += a * b ;
			}
		}
		StringBuffer res = new StringBuffer();		
		for(int i = 0; i < len1 + len2   ;i++) {
			res.append(ans[i] % 10);
			ans[i + 1] += ans[i] / 10;
		}
		String result = res.reverse().toString();
		if(result.startsWith("0"))
			result = result.substring(1, len1 + len2);
		return result;
	}  

測試用例


其他

程式碼託管碼雲地址:https://gitee.com/lizhaoandroid/LeetCodeAll.git

檢視其他內容可以點選專欄或者我的部落格哈:https://blog.csdn.net/cmqwan

“大佬們的答案” 標籤來自leetcode,侵權請聯絡我進行刪改

如有疑問請聯絡,聯絡方式:QQ3060507060