北大OJ1001

  1 #include<iostream>
  2 #include<string>
  3 using namespace std;
  4 
  5 string add(string str1, string str2)
  6 {
  7     string str;
  8 
  9     string::size_type L1,L2;
 10     int i;
 11     L1=str1.size();
 12     L2=str2.size();
 13     if (L1<L2) {
 14         for (i=1;i<=L2-L1;i++) str1="0"+str1;
 15     } else {
 16         for (i=1;i<=L1-L2;i++) str2="0"+str2;
 17     }
 18     int int1=0,int2=0; //int2 记录进位
 19     for (i=str1.size()-1;i>=0;i--) {
 20         int1=(int(str1[i])-'0'+int(str2[i])-'0'+int2)%10;
 21         int2=(int(str1[i])-'0'+int(str2[i])-'0'+int2)/10;
 22         str=char(int1+'0')+str;
 23     }
 24     if (int2!=0) str=char(int2+'0')+str;
 25 
 26     return str;
 27 }
 28 
 29 string mul(string str1, string str2)
 30 {
 31     string str;
 32     string::size_type L1 = str1.size();
 33 
 34     int i,j;
 35     for(i = 4; i >= 0; i--)
 36     {
 37         string tempstr;
 38         int int1 = 0, int2 = 0, int3 = int(str2[i]) - '0';
 39 
 40         
 41         for (j=1;j<=(int)(4-i);j++) tempstr="0"+tempstr;
 42         for (j=L1-1;j>=0;j--) {
 43             int1=(int3*(int(str1[j])-'0')+int2)%10;
 44             int2=(int3*(int(str1[j])-'0')+int2)/10;
 45             tempstr=char(int1+'0')+tempstr;
 46         }
 47         if (int2!=0) tempstr=char(int2+'0')+tempstr;
 48         
 49         str=add(str,tempstr);
 50     }
 51 
 52     return str;
 53 }
 54 
 55 int main()
 56 {
 57     string R, ans;
 58     int n, toEnd;
 59     while(cin>>R>>n)
 60     {
 61         
 62         //find the position of decimal point
 63         if(R[1] == '.')
 64         {
 65             toEnd = 4;
 66             R.erase(1,1);
 67         }
 68         else 
 69         {
 70             toEnd = 3;
 71             R.erase(2,1);
 72         }
 73         ans = R;
 74 
 75         for(int i = 1; i < n; i++)
 76         {
 77             ans = mul(ans, R);
 78         }
 79 
 80         string::size_type L2 = ans.size();
 81         
 82         //add decimal point
 83         ans.insert(L2-n*toEnd, 1, '.');
 84 
 85         int m = L2;
 86         while(ans[m] == '0')
 87         {
 88             ans.erase(m,1);
 89             m--;
 90         }
 91 
 92         int k = 0;
 93         while(ans[k] == '0')
 94         {
 95             ans.erase(k,1);
 96         }
 97         
 98 
 99         cout<<ans;
100     }
101 
102     return 0;
103 }

问题:

http://poj.org/problem?id=1001

思路:

先找到小数点位置,然后按照大整数相乘来做。把数字存储为string类型。

参考:

http://bbs.csdn.net/topics/390881136

 

posted on 2015-08-23 17:13  Sipin  阅读(324)  评论(0编辑  收藏  举报

导航