编程算法 - 大整数乘法

大整数乘法


本文地址: http://blog.csdn.net/caroline_wendy/article/details/29353263


题目:

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

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


代码:

/*
 * test.cpp
 *
 *  Created on: 2014.04.24
 *      Author: Spike
 */

/*eclipse cdt, gcc 4.8.1*/

#include 
#include 

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, 0, 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]);
    }
    result[len_a+len_b] = '\0'; //添加结束符

    delete[] num_arr;

    return result;
    //delete[] r;
}

int main(void){
    char* number_a = "10089328947197491751797009791032";
    char* number_b = "837190274291741974109721921321451";
    std::cout << number_a << " * " << number_b << " = " << std::endl;

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

    delete[] result;
    return 0;
}

输出:

10089328947197491751797009791032 * 837190274291741974109721921321451 = 
08446688068723880396297437187783381747295407214602740206809027432


编程算法 - 大整数乘法_第1张图片



你可能感兴趣的:(Mystra,编程算法,大整数乘法,字符串,C++,Algorithm)