求2的100次方的算法

2024-11-26 18:47:31
推荐回答(1个)
回答1:

求2的100次方,用整形存储会产生逸出,因此用字符串存储结果,其算法如下:
#include
#include
char * pow2(int power)
{
int i,j;
int carry = 0; //进位
bool bBeginMove = false;
if (power < 0)
return NULL; //为了简便此处不考虑小于0的情况
char len = power > 2 ? power : 2;//申请的空间长度至少为2
char * number = new char[len];
memset(number,0,len);
number[len - 1] = 1;

for (i = 1; i <= power; i++)
{
for (j = len - 1; j >= 0; j--)
{
number[j] = number[j] * 2 + carry;
if (number[j] >= 10)
{
carry = 1; //大于十需要进位
number[j] = number[j] % 10;
} else {
carry = 0; //否则无需进位
}
}
}
//将数据移动到数组的前端
for(i = 0,j = 0; i < len; i++)
{
if (number[i] != 0)
{
int tmp = number[i];
number[i] = 0;
number[j++] = tmp + '0';
bBeginMove = true;
} else if (bBeginMove) {
number[j++] = '0';
}
}
return number;
}
void main()
{
char * pow_2;
pow_2 = pow2(100);
printf("%s",pow_2);
delete[]pow_2;
}