POJ——1001 求高精度幂

来源:互联网 发布:虚拟桌面软件 编辑:程序博客网 时间:2024/04/29 06:40

#include<iostream>#include<stdio.h>#include<string>#include<vector>#include<string.h>const int  MAX = 1000;using namespace std;string multi(string a, string b);int main(){string R;int n;int point;while(cin>>R>>n){bool flag = false;for(int i = 0; i < R.length(); i++) {if(R[i] == '.'){flag = true;    //是否有小数点的标志                          break;}} //无小数点时,考虑头部是否有0if(flag == false){for(; ;) {    if(R[0] == '0'){string::iterator it1 = R.begin(), it2 = R.begin()+1;R.erase(it1, it2);}elsebreak;}if(R.length() == 0){cout<<0<<endl;continue;}}//有小数点的if(flag == true){  for(int  i = R.length()-1; i >= 0; i--)    //  有小数点的,去头去尾{if(R[i] == '0'){string::iterator it1 = R.end()-1, it2 = R.end();R.erase(it1, it2);}elsebreak;}for(; ;)                      {if(R[0]=='0'&&R[1]=='.')break;if(R[0] == '0'){string::iterator it1 = R.begin(), it2 = R.begin()+1;R.erase(it1, it2);}elsebreak;}}if(flag == true){  for(int i = 0; i < R.length(); i++) {if(R[i] == '.'){if(i == R.length()-1){flag = false;}        point = R.length() - i - 1;               break;}}     R = R.erase(R.length()-point-1,1);  //有小数点时,先去掉小数点}string str = R;for(int i = 2; i <= n; i++)    //循环相乘{  str = multi(str, R);} if(flag == true)    //有小数点,要加上小数点{point = point*n;int set_where = str.length() - point;str.insert(set_where,".",1);}if(flag == true)            //去掉尾部和首部的0,前提是有小数点{for(int  i = str.length()-1; i >= 0; i--)  {if(str[i] == '0'){string::iterator it1 = str.end()-1, it2 = str.end();str.erase(it1, it2);}elsebreak;}for(int  i = 0; ; i++)                       //去掉首部的0,关键点,每次都是str[0]进行比较{if(str[0] == '0'){string::iterator it1 = str.begin(), it2 = str.begin()+1;str.erase(it1, it2);}elsebreak;}}cout<<str<<endl;}return 0; }string multi(string a, string b)    //两个大整数相乘的定义{int num_a[MAX], num_b[MAX];    int plus[MAX*2];memset(plus, 0, sizeof(plus));num_a[0] = a.length();num_b[0] = b.length();for(int i = 1; i <= num_a[0]; i++)    //把字符串存到整型数组里num_a[i] = a[i-1]-48;for(int i = 1; i <= num_b[0]; i++)num_b[i] = b[i-1]-48;              for(int i = 1; i <= num_a[0]; i++)     //每一位分别进行相乘,用一个新的数组存储   {   for(int j = 1; j <= num_b[0]; j++)   {   plus[i+j] += num_a[i]*num_b[j];   }   }   for(int  i = num_a[0]+num_b[0]; i >= 2; i--)  //分别进位保留个位数   {   plus[i-1] += plus[i]/10;   plus[i] %= 10;   }                                   //确定相乘后的结果的位数   if(plus[1] == 0)    {   plus[0] = num_a[0]+num_b[0]-1;   for(int i = 2; i <= num_a[0]+num_b[0]; i++)   plus[i-1] = plus[i];   plus[num_a[0]+num_b[0]] = 0;   }   else       plus[0] = num_a[0]+num_b[0];   string str_plus = "";   for(int i = 1; i <= plus[0]; i++)   {   char ch[5];      sprintf(ch, "%d",plus[i]);   string temp(ch);   str_plus = str_plus + ch;   }   return str_plus;}

0 0
原创粉丝点击