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();
}

  

原文链接: https://www.cnblogs.com/chinadx/archive/2012/12/05/2803581.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

    Problem 16

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/71595

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月9日 下午2:56
下一篇 2023年2月9日 下午2:56

相关推荐