POJ 1001 Exponentiation

给出一个实数x和一个整数n

求x^n

这是一道高精度题,把实数转化为整数后解决,处理小数点位置即可

(破题写了一上午)

#include<cstdio>
#include<algorithm>
#include<cstring>
#include<cmath>
using namespace std;
const int N=1e5+5;
struct name
{
  int s[N],l;
  name(){memset(s,0,sizeof(s));}
  void push()
  {
    int ll=l;
    for(int i=0;i<2*ll;i++)
      {
    s[i+1]+=s[i]/10;
    s[i]%=10;
    if(s[i]!=0) l=max(l,i);
      }
  }
  void pushup(int x)
  {
    s[x+1]+=s[x]/10;
    s[x]%=10;
    if(s[x+1]!=0) l=max(l,x+1);
    if(s[x]!=0) l=max(l,x);
  }
  friend inline name operator *(const name &x,const name &y)
  {
    name ret;
    int l1=x.l,l2=y.l;
    //    for(int i=l1-1;i>=0;i--) printf("%d",x.s[i]);putchar('*');
    //    for(int i=l2-1;i>=0;i--) printf("%d",y.s[i]);putchar('=');
    ret.l=l1+l2;
    for(int i=0;i<l1;i++)
      for(int j=0;j<l2;j++)
    ret.s[i+j]+=x.s[i]*y.s[j],ret.pushup(i+j);
    ret.push();
    //int l3=ret.l;
    //for(int i=l3-1;i>=0;i--) printf("%d",ret.s[i]);putchar('\n');
    return ret;
  }
}a,ans;
name qpow(name x,int y)
{
  name ret=x;y--;
  while(y)
    {
      if(y&1) ret=ret*x;
      x=x*x;
      y>>=1;
    }
  return ret;
}
char str[N],S[N];
int n;
int main()
{
  while(~scanf("%s%d",str,&n))
    {
      int l=strlen(str),pos=-1;
      a.l=0;
      for(int i=l-1,j=0;i>=0;i--,j++)
    {
      if(str[i]=='.')
        {
          pos=j;
          continue;
        }
      a.s[a.l++]=str[i]-'0';
    }
      ans=qpow(a,n);
      l=ans.l;
      //printf("Y%dY\n",pos);
      pos=pos*n;
      //printf("Z%dZ\n",pos);
      int st=0,ed=-1;
      for(int i=l-1,j=0;i>=0;i--,j++)
    {
      if(i==pos-1)S[++ed]='.';
      S[++ed]=ans.s[i]+'0';
      //printf("%d",ans.s[i]);
    }
      //putchar('\n');
      while(S[st]=='0') st++;
      if(pos!=-1)while(S[ed]=='0') ed--;
      if(S[ed]=='.')ed--;
      if(st>ed) putchar('0');
      for(int i=st;i<=ed;i++) printf("%c",S[i]);
      putchar('\n');
    }
  return 0;
}

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325256177&siteId=291194637