数据结构和算法分享专题程序员unity3D技术分享

大数乘法

2016-09-07  本文已影响136人  编码的哲哲

算法爬坑之线性表大数乘法

WAI0`%JDC1P({JBR$DE{F}O.jpg

include<iostream>

include<memory.h>

include<string.h>

using namespace std;

int* multi(int* num1, int size1, int* num2, int size2){

int size = size1 + size2;
int* ret = new int[size];
int  i   = 0;

memset(ret, 0, sizeof(int) * size);


for(i = 0; i<size2; ++i){
    
    int k = i;
    for(int j = 0; j < size1; ++j){
        
        ret[k++] += num2[i] * num1[j];          
    }
    
    
}



for (i = 0; i < size; ++i){
    
    if(ret[i] >= 10){
        
        ret[i+1] += ret[i]/10;
        ret[i]   %= 10;
    }
}



return ret;

}

int main(int argc, char** argv) {

char digit1[100];
char digit2[100];

cin >> digit1 >> digit2;

int size1 = strlen(digit1);
int size2 = strlen(digit2);

int* num1 = new int[size1];
int* num2 = new int[size2];

int* currentDigit1 = new int[size1];
int* currentDigit2 = new int[size2];

for(int j = 0, jj = size1 - 1; j < size1; j++, jj--){
    
    num1[jj] = digit1[j] - '0'; 
}

for(int k = 0, kk = size2 - 1; k < size2; k++, kk--){
    
    num2[kk] = digit2[k] - '0'; 
}
    

int* ret = multi(num1, size1, num2, size2);

cout<<"求得的乘积为:"<<endl; 
for(int i = size1+size2-2; i >= 0 ; i--){
    
    cout << ret[i];
    
}

delete[] ret;
return 0;

}

上一篇下一篇

猜你喜欢

热点阅读