好久没有敲代码了,这么水的一题我敲了2个小时= =!
主要考察高精度算法,注意判定条件,给定小数位,什么时候改把零省略,什么时候不可以。只有是在整数部分的前置零可以省略,结尾的零最后输出地时候处理一下。写得好丑啊~~~~
#include<iostream>
#include<cstring>
#include<cstdio>
using namespace std;
const int N = 200;
class Bign{
public:
Bign(){
count = dot = 0;
}
void set(char *ss){
int l = strlen(ss);
count = dot = 0;
int j = 0;
for(int i = l-1;i>=0;i--){
if(ss[i]=='.'){
dot = j;
continue;
}
s[j++] = ss[i]-'0';
}
count = j;
}
void init(){
count = 1;
dot = 0;
s[0] = 1;
}
void reset(){
memset(s,0,sizeof(s));
}
int s[N];
int count;
int dot;
};
Bign mul(Bign a,Bign b){
int carry = 0;
int i,j;
Bign result;
result.reset();
for(i = 0;i<a.count;i++){
carry = 0;
for(j=0;j<b.count || carry;j++){
carry = carry+result.s[i+j];
if(j<b.count)carry+=a.s[i]*b.s[j];
result.s[i+j]=carry%10;
carry/=10;
}
}
int l = a.count+b.count+1;
result.dot = a.dot+b.dot;
while(l && result.s[l]==0 && l>result.dot){
l--;
}
if(l==0)result.count = 1;
else result.count = l+1;
return result;
}
char R[8];
int n;
Bign pow(Bign a,int nn){
Bign tmp;
if(nn==0){
tmp.init();
return tmp;
}
if(nn==1)return a;
if(nn%2==1){
tmp = a;
Bign tmp = pow(a,nn/2);
tmp = mul(tmp,tmp);
return mul(tmp,a);
//return
}else {
tmp = pow(a,nn/2);
return mul(tmp,tmp);
}
}
void p(Bign result){
///printf("%d\n%d\n",result.dot,result.count);
if(result.dot==0){
for(int i = result.count-1;i>=0;i--)printf("%d",result.s[i]);
printf("\n");
}
else if(result.dot>result.count){
printf(".");
for(int i = 0;i<result.dot-result.count;i++)printf("0");
int bottom = 0;
while(result.s[bottom]==0)bottom++;
for(int i = result.count-1;i>=bottom;i--)printf("%d",result.s[i]);
printf("\n");
}else{
int bottom = 0;
while(result.s[bottom]==0 && bottom<result.dot)bottom++;
bool istrue = false;
for(int i = result.count-1;i>=bottom;i--){
if(!istrue && result.s[i]==0);
else {
istrue = true;
printf("%d",result.s[i]);
}
if(i==result.dot && result.dot!=bottom){
printf(".");
istrue = 1;
}
}
printf("\n");
}
}
void solve()
{
Bign r;
r.set(R);
r = pow(r,n);
p(r);
}
int main()
{
while(scanf("%s%d",&R,&n)!=EOF){
solve();
}
return 0;
}