Problem 16
Problem 16
03 May 2002
215 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26.
What is the sum of the digits of the number 21000?
|
Answer:
|
1366 |
C++貌似没有现成的对超大数字的支持,我写了个用来计算超大数字的类。为了简单,没有动态分配数组长度。
//设置长数字的最大容量
const int MAX_LENGTH = 1000;
//计算数字的位数
int GetDigitCount(int n)
{
int c = 0 ;
while (n)
{
n /= 10 ;
++c ;
}
return c ;
}
class BigNum
{
public:
BigNum();
BigNum(int num);
BigNum(const char* num);
~BigNum();
void print();
friend BigNum& operator*(BigNum& lNum, const int rNum);
private:
int _len;
int _top;
int* _array;
};
BigNum::BigNum()
{
_len = 0;
_top = 0;
_array = new int[0];
}
BigNum::BigNum(int num)
{
_len = MAX_LENGTH;
_top = GetDigitCount(num);
_array = new int[MAX_LENGTH];
int res = num;
for(int i=0; i<_top; i++)
{
_array[i] = res%10;
res = res/10;
}
}
BigNum::~BigNum()
{
delete[] _array;
}
void BigNum::print()
{
long sum=0L;
cout<<"The Big Number is:";
for(int i=_top; i>0; i--)
{
cout<<_array[i-1];
sum+=_array[i-1];
}
cout<<endl;
cout<<"sum of the digits is:"<<sum<<endl;
}
BigNum& operator*(BigNum& lNum, const int rNum)
{
int rem = 0;
for(int i=0; i<lNum._top; i++)
{
int tmp = (lNum._array[i])*rNum +rem;
lNum._array[i] = tmp%10;
rem=tmp/10;
}
//处理剩余的进位,需要将原数字的长度递增
while(rem)
{
lNum._array[lNum._top++]=rem%10;
rem/=10;
}
return lNum;
}
void p16()
{
BigNum bn(2);
BigNum ab=bn;
BigNum tt;
for(int i=0;i<999;i++)
{
tt=ab*2;
ab=tt;
}
ab.print();
}

浙公网安备 33010602011771号