线性表-大整数乘法(数据结构基础 第2周)

问题描述:
线性表-大整数乘法(数据结构基础 第2周)_第1张图片
分析
注意处理好进位、某一位原有数字及最高一位,常规题。
源码

#include <iostream>
#include <vector>
#include <string>
using namespace std;

int main() {
    string s1, s2;
    cin >> s1 >> s2;    
    int len1=s1.length(), len2=s2.length();
    vector<int> a, b, sum(len1+len2, 0);
    if (len1>len2) {
        for(int i=len1-1; i>=0; i--) {
            a.push_back(s1[i]-'0');
        }
        for (int i=len2-1; i>=0; i--) {
            b.push_back(s2[i]-'0');
        }
    }
    else {
        for (int i=len2-1; i>=0; i--) {
            a.push_back(s2[i]-'0');
        }
        for(int i=len1-1; i>=0; i--) {
            b.push_back(s1[i]-'0');
        }   
    }
    int temp=0;
    int i, j;
    for (i=0; i<b.size(); i++) {
        int carry=0;
        for (j=0; j<a.size(); j++) {
            temp=a[j]*b[i]+carry+sum[i+j];
            sum[i+j] = temp%10;
            carry = temp/10;
        }
        sum[i+j] += carry;  //补上最后一个的进位
    }
    bool flag=false;
    for (int i=sum.size()-1; i>=0; i--) {
        if (flag==false && sum[i]==0) {
            continue;
        }
        flag=true;
        cout << sum[i];
    }
    return 0;
}

你可能感兴趣的:(线性表-大整数乘法(数据结构基础 第2周))