首页 > 试题广场 >

字符串相乘

[编程题]字符串相乘
  • 热度指数:5308 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 32M,其他语言64M
  • 算法知识视频讲解
给定两个数字(0-9)字符串(长度不限)求它们的乘积。

输入描述:
第一行为第一个数字字符串

第二行为第二个数字字符串


输出描述:
乘积字符串
示例1

输入

123
20

输出

2460
# 模拟了一遍乘法运算
def strAdd(s1, s2):
    res, carry = '', 0
    l1, l2 = len(s1)-1, len(s2)-1
    while l1 >= 0 and l2 >= 0:
        a, b = s1[l1], s2[l2]
        r = int(a)+int(b)+carry
        carry = r//10
        res = str(r % 10)+res
        l1 -= 1
        l2 -= 1

    def continueAdd(l, s, carry):
        nonlocal res
        while l >= 0:
            a = s[l]
            r = int(a)+carry
            carry = r//10
            res = str(r % 10)+res
            l -= 1
    if l1 >= 0:
        continueAdd(l1, s1, carry)
    elif l2 >= 0:
        continueAdd(l2, s2, carry)
    return res
def findZero(s):
    t,i,n=s[-1],len(s)-1,0;
    while t=='0':
        i-=1;
        t=s[i];
        n+=1;
    return s[:i+1],n
    
def strMulti(n,s):
    f=[str(n*int(i)) for i in s[::-1] ]
    res=f[0];
    i=-1;
    for s in f[1:]:
        res=strAdd(s,res[:i])+res[i:];
        i-=1;
    return res;
s1=input()
s2=input();
s1,a=findZero(s1);
s2,b=findZero(s2);
zero=a+b;
s1=int(s1);
s2=int(s2);
if (len(str(s1))>len(str(s2))):
    print(strMulti(s1,str(s2))+'0'*zero)
else:
    print(strMulti(s2,str(s1))+'0'*zero)
        

发表于 2020-04-14 15:42:19 回复(0)
# 大整数相乘
s1 = input()
s2 = input()

nums = [0]*(len(s1) + len(s2))

s3 = s1[::-1]
s4 = s2[::-1]

for i in range(len(s3)):
    for j in range(len(s4)):
        nums[i+j] += int(s3[i])*int(s4[j])

for i in range(len(nums)-1):
    nums[i+1] += nums[i] // 10
    nums[i] = nums[i] % 10

res = ''
for i in range(len(nums)-1, -1, -1):
    if i==len(nums)-1:
        if nums[i] == 0:
            continue
        else:
            res += str(nums[i])
    else:
        res += str(nums[i])
ind = 0
while ind < len(nums):
    if res[ind] == '0':
        ind += 1
    else:
        break
print(res[ind:])

发表于 2019-08-31 15:30:24 回复(0)
if __name__ == "__main__":
    a = int(raw_input().strip())
    b = list(map(int, raw_input().strip()))

    ans = 0
    i = 0
    for j in b[::-1]:
        ans += a * j * 10**i
        i += 1

    print ans

编辑于 2019-08-29 20:18:26 回复(0)

一行

print(int(input()) * int(input()))
发表于 2019-07-20 07:58:15 回复(0)

a = int(input())
b = int(input())
print(a*b)

哈哈哈,再也不用C++写大整数了
编辑于 2019-03-04 10:07:34 回复(0)