大数相乘
发布时间:2020-12-14 03:03:08 所属栏目:大数据 来源:网络整理
导读:无意中看到一个华为面试题,使用代码计算 1234567891011121314151617181920*2019181716151413121110987654321。自己搞了一上午。写的真烂,贴上来,大家笑话去吧。 整体思想很简单,就是用字符数组代替数值,小学乘法的思想用在程序里。学好数学的重要性,程
无意中看到一个华为面试题,使用代码计算1234567891011121314151617181920*2019181716151413121110987654321。自己搞了一上午。写的真烂,贴上来,大家笑话去吧。 整体思想很简单,就是用字符数组代替数值,小学乘法的思想用在程序里。学好数学的重要性,程序再牛逼,也得先会数学。
#include<iostream> using namespace std; char bigA[100]; char bigB[100]; static char bigResult[200]; static int sum = 0; void merge(char temp[]); void printResult(); void cheng(char bigA[],char bigB[]){ //大数A的从低位到高位分割 for(int i=strlen(bigA)-1; i>= 0; i--){ int chengA = bigA[i] - 48;//对应大数A的每一位单位乘数 //大数B从低位到高位分割 for(int j=strlen(bigB)-1; j>= 0;j--){ int chengB = bigB[j] - 48;//对应大数B的每一位单位乘数 int result = chengA * chengB; if(result > 9){//对应的就是结果是两位 int count = strlen(bigA)-1 - i + strlen(bigB)-1 - j + 2; char temp[100]; temp[0]=49; temp[1]=result-10+48; for(int n = 2; n < count; n++){ temp[n]='0'; } temp[count]=' '; merge(temp); //cout<<temp; }else{//对应就是结果为1位 int count = strlen(bigA)-1 - i + strlen(bigB)-1 - j + 1; char temp[100]; temp[0]=result+48; for(int n = 1; n < count; n++){ temp[n]='0'; } temp[count]=' '; merge(temp); //cout<<temp; } //printResult(); } } } void init(){ for(int i = 0; i<200; i++){ bigResult[i]='0'; } bigResult[200]=' '; } //bigResult就是从低位到高位记录的 void merge(char temp[]){ int k=0; int jin = 0; for(int i = strlen(temp)-1; i>=0; i--){ int jiaA = bigResult[k] - 48; int jiaB = temp[i] - 48; int result = jiaA + jiaB + jin - 10; if(result >= 0){ bigResult[k]=result+48; jin = 1; }else{ bigResult[k]=result+10+48; jin = 0; } k++; } while(jin != 0){ int jia = bigResult[k]-48; int result = jia + jin - 10; if(result >=0){ bigResult[k]=result+48; jin = 1; }else{ bigResult[k]=result+10+48; jin=0; } k++; } sum = sum > k ? sum : k; } //输出结果 void printResult(){ //cout<<sum<<endl; cout<<"The Result: "; for(int i = sum-1; i >= 0 ; i--){ cout<<bigResult[i]; } cout<<endl; } int main(){ //cout<<sizeof(char)<<endl; //char*temp = (char*)malloc(sizeof(char)*1); //cout<<strlen(temp)<<endl; init(); cin>>bigA; cin>>bigB; cheng(bigA,bigB); printResult(); system("pause"); } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |