题目:
小明是个小学五年级的学生,为了早点去看自己爱看的卡通,他想快点把作业做完。可是可恶的数学老师今天却布置了一道难题,小明想了很久也不知道该怎么做。你的任务就是帮小明解决掉这道数学题。
题目是这样子的,有一个整数a(-2^31<= a < 2^31-1),计算它的整数幂a^n,其中1<=n<=99。
输入
第一行是一个整数K,表示有多少个测试用例,以后每行一个测试用例,每行有两个整数a,n。
输出
每行输出一个测试用例的结果。
示例输入
2 3 5 -2 5
示例输出
243 -32
#include<iostream>
#include<cstring>
using namespace std;
const int size=1000; //大数位数
char a[size+1]; //存储大数
char a2[size+1]; ///暂存负的值
char ans[size*size+1]; //存储结果
void mult(char* A,char* B,char* ans)
{
int a[size+1]={0};
int b[size+1]={0};
int pa=0,pb=0;
int c[2*size+1]={0};
int i,j;
int lena=strlen(A);
int lenb=strlen(B);
for( i=lena-1;i>=0;i--)
a[pa++]=A[i]-'0';
for( j=lenb-1;j>=0;j--)
b[pb++]=B[j]-'0';
for(pb=0;pb<lenb;pb++)
{
int w=0; //低位到高位的进位
for(pa=0;pa<=lena;pa++)
{
int temp=a[pa]*b[pb]+w;
w=temp/10;
temp=(c[pa+pb]+=temp%10);
c[pa+pb]=temp%10;
w+=temp/10;
}
}
bool flag=false;
bool sign=false; //标记ans是否为全0
for(pa=0,pb=lena+lenb-1;pb>=0;pb--)
{
if(!flag && c[pb]==0) //删除ans开头的0
continue;
else
flag=true;
sign=true;
ans[pa++]=c[pb]+'0';
}
if(sign)
ans[pa]='\0';
else
{
ans[0]='0';
ans[1]='\0';
}
return;
}
int main()
{
int t,b,len;
int i,j;
cin>>t;
while(t--)
{
cin>>a>>b;
ans[0]='1';
ans[1]='\0';
if(a[0]!='-')
{
for(i=1;i<=b;i++)
mult(a,ans,ans);
cout<<ans<<endl;
}
else
{
len=strlen(a);
for( j=1;j<len;j++)
a2[j-1]=a[j];
a2[j-1]='\0';
for( i=1;i<=b;i++)
{
mult(a2,ans,ans);
}
if(b%2==0)
cout<<ans<<endl;
else
cout<<"-"<<ans<<endl;
}
}
return 0;
}
注意:
在求解过程中,注意有符号的变化,当输入负数时,奇次幂为奇数,偶次幂为偶数!