日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學(xué)無先后,達(dá)者為師

網(wǎng)站首頁 編程語言 正文

python?實現(xiàn)兩個字符串乘法小練習(xí)_python

作者:驚瑟 ? 更新時間: 2022-04-25 編程語言

兩個字符串相乘,基本思路是num1依次乘以num2各個數(shù)位上的數(shù)字,再將其累加,如下圖所示:

需要注意的是,對于高位的乘積,需要在后面補0,0的個數(shù)和num2的數(shù)位有關(guān)系,十位補1個0,百位補2個0,假設(shè)num2的長度為n,從左到右對其數(shù)位編號為0、1、2...i,總結(jié)規(guī)律為:補0的個數(shù)=n-1-i。

以下是具體代碼:

#兩個字符串相乘
#基本思路是num1依次乘以num2各個數(shù)位上的數(shù)字,再將其累加
?
from add_strings import add_strings1 # add_strings1 作用是使兩個字符串相加,可以參考前面的文章
?
def mutiply_strings(num1,num2):
? ? res = '' ?# 最終的結(jié)果
? ? len_num1 = len(num1)
? ? len_num2 = len(num2)
?
? ? # 使num1從左到右(方向無所謂,只要定義好每個數(shù)位的權(quán)即可)乘以num2各個數(shù)位,最后再相加
? ? for i in range(len_num2):
? ? ? ? carry = 0 ?# 進(jìn)位
? ? ? ? w = len_num2-1-i # 權(quán)值,有幾個就需要在計算結(jié)果后面補幾個零
? ? ? ? curRes = w*'0' # 本次運算的結(jié)果
?
? ? ? ? for j in range(len_num1):
? ? ? ? ? ? x = num1[len_num1-1-j] # 反序,因為num1要從右向左依次乘
? ? ? ? ? ? product = (ord(x)-ord('0'))*(ord(num2[i])-ord('0'))
? ? ? ? ? ? tmp = str((product+carry)%10)
? ? ? ? ? ? carry = int((product+carry)/10)
? ? ? ? ? ? curRes = tmp + curRes
? ? ? ? if carry: # 最高位若有進(jìn)位需要加上
? ? ? ? ? ? curRes = str(carry) + curRes
? ? ? ? #print(curRes)
? ? ? ? res = add_strings1(res,curRes) # 累加每層的結(jié)果
? ? return res
?
?
if __name__ == '__main__':
? ? print(mutiply_strings('234','234'))
? ? print(mutiply_strings('123456789','987654321'))
? ? print(123456789*987654321)

原文鏈接:https://blog.csdn.net/qq_34062683/article/details/121737917

欄目分類
最近更新