Leetcodes Solution 43 Multiply Strings

匯總

雪之下雪乃:leetcode解題總匯?

zhuanlan.zhihu.com圖標

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

Note:

  1. The length of both num1 and num2 is < 110.
  2. Both num1 and num2 contains only digits 0-9.
  3. Both num1 and num2 does not contain any leading zero.
  4. You must not use any built-in BigInteger library or convert the inputs to integer directly.

思路1

用carry來表示滿10的進位

class Solution{public: string multiply(string num1, string num2){ string sum(num1.size() + num2.size(), 0); for(int i = num1.size() - 1; i >= 0; --i){ int carry = 0; for(int j = num2.size() - 1; j >= 0; --j){ int tmp = (sum[i + j + 1] - 0) + (num1[i] - 0) * (num2[j] - 0) + carry; sum[i+j+1] = tmp % 10 + 0; carry = tmp / 10; } sum[i] += carry; } size_t startpos = sum.find_first_not_of("0"); if(string::npos != startpos) return sum.substr(startpos); return "0"; }};

推薦閱讀:

地圖生成與C4D聯動
如何後台掛爾雅通識課?
這可能是我見過最好的編程指南了!
Python分詞模塊jieba (01)-jieba安裝,分詞,提取關鍵詞,自定義分詞,切換詞庫講解
Scratchapixel舉步維艱,尋求贊助或投放廣告

TAG:演算法 | 編程 | 數據結構 |