加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

数据结构-----大数编程算法的实现

发布时间:2020-12-14 03:33:36 所属栏目:大数据 来源:网络整理
导读:题目: 大整数乘法,给定两个长度不超过10000的整数,返回乘法的结果. char* multi(char* number_a,char* number_b) #include iostream#include cstringusing namespace std;char* multi(char* number_a,char* number_b) { int len_a = strlen(number_a); //计

题目:

大整数乘法,给定两个长度不超过10000的整数,返回乘法的结果.

char* multi(char* number_a,char* number_b)


#include <iostream>
#include <cstring>

using namespace std;

char* multi(char* number_a,char* number_b) {

    int len_a = strlen(number_a); //计算长度
    int len_b = strlen(number_b);

    int* num_arr = new int[len_a+len_b];
    memset(num_arr,sizeof(int)*(len_a+len_b)); //置0

    for (int i=len_a-1; i>=0; --i) { //计算每一位
        for (int j=len_b-1; j>=0; --j) {
        num_arr[i+j+1] += (number_b[j]-'0')*(number_a[i]-'0');
        }
    }

    for (int i=len_a+len_b-1; i>=0; --i) { //进位
        if (num_arr[i] >= 10) {
        	num_arr[i-1] += num_arr[i]/10;
        	num_arr[i] %= 10;
        }
    }

    char* result = new char[len_a+len_b+1];

    for( int i=0; i<(len_a+len_b); ++i){
    	result[i] = (char)(((int)'0')+num_arr[i]);
    }

    //如果收尾为0则消除
    if(result[0]=='0')
    {
        for( int i=0; i<(len_a+len_b)-1; ++i)
        {
    	result[i] = result[i+1];
        }
        result[len_a+len_b-1] = ''; //添加结束符
    }
    else
    {
         result[len_a+len_b] = ''; //添加结束符
    }

    delete[] num_arr;

    return result;
}

int main(){
    char number_a[] = "10089328947197491751797009791032";
    char number_b[] = "837190274291741974109721921321451";
   //char number_a[] = "99";
    //char number_b[] = "999";
    std::cout << number_a << " * " << number_b << " = " << std::endl;

    char* result = multi(number_a,number_b);
    std::cout << result << std::endl;

    delete[] result;
    return 0;
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读