pku1001

来源:互联网 发布:软件研发部助理 编辑:程序博客网 时间:2024/05/02 02:49


这段时间面试,国考,回家。。哎 终于开始研究算法题目了。

题目就不放了。。pku1001,可以去网站上看,大体说下思路吧。

一、大数乘法:方法是用两个字符数组来存储(这个地球人都知道),但在算的时候有个小技巧,用相应的整数数组来存储结果,之后在转换回去,而为了进位,在存储运算结果时需要位置坐标+1。说的不太清楚,看下面代码就会了解。

二、由于题目中对输出的结果有限制,必须分清小数点的各种情况(逻辑能力)。

三、注意是对char进行操作,不要分配空间不够导致结尾的'\0'也被改动了,使得strlen函数出错(细心)。

如果觉得一次就能被accept就直接跳过吧。。小菜我可是改了一下午的。。

#include<iostream>#include<string.h>#include<string>using namespace std;void BigMulti(const char *a,int n){int mov = 0;int dot = -1;int shift = 0,begin = 0;int digit = strlen(a);char *result = (char *)malloc(sizeof(char)*digit);memset(result,0,digit);for(int pos = 0;a[pos] != '\0';++pos){if(a[pos] == '.'){dot = pos;break;}}if(dot == -1 || dot == (digit-1) ){int pos = 0;while(a[pos] == '0')pos++;while( a[pos] != '\0' && a[pos] != '.')result[pos] = a[pos++];}else{int pos = digit-1;while(a[pos] == '0'){++shift;--pos;}pos =0;while(a[pos] == '0')pos++;int begin =0;while(pos < digit-shift){if(a[pos] != '.')result[begin++] = a[pos];pos++;}mov = (digit-dot-shift-1)*n;}//multiply nowdigit = strlen(result);char *t_result = (char *)malloc(sizeof(char)*(n*digit+1));memset(t_result,0,n*digit+1);int pos =0;while(result[pos] != '\0')t_result[pos] = result[pos++];while(n>1){int t_digit = strlen(t_result);int *temp = (int *)malloc(sizeof(int)*(t_digit+digit));for(int i =0;i<(t_digit+digit);++i)temp[i] = 0;for(int m=0;m < t_digit;m++)for(int k=0;k< digit;k++)temp[m+k+1] += (t_result[m]-'0')*(result[k]-'0');for(int i = t_digit+digit-1;i>0;--i){if(temp[i] >= 10){temp[i-1] += temp[i]/10;temp[i] %= 10;}}int pos =0;while(temp[pos] == 0)pos++;for(int j = 0;pos<t_digit+digit;j++)t_result[j] = (temp[pos++]+'0');free(temp);n--;}if(mov == 0)cout<<t_result;else{digit = strlen(t_result);pos = digit-mov;int i =0;if(pos <= 0){cout<<'.';for(int j =0;j< -pos;j++)cout<<0;}else{for(;i <pos; i++)cout<<t_result[i];cout<<'.';}while(i <digit)cout<<t_result[i++];}cout<<endl;free(result);free(t_result);;}int main(){string s;int n;while(cin>>s>>n){const char *a = s.c_str();BigMulti(a,n);}return 0;}

0 0