大数处理之:能被六整除的数串

有一个数字串,他的长度超出最长整形的处理范围,请确定该数串是否能够被六整除。

 

源码如下,请大家批评指正。

 

#include <stdio.h>
#include <iostream>
 
using namespace std;
 
class CDoubleSix
{
public:
    CDoubleSix();
    ~CDoubleSix();
public:
    int CanDividedBySix( const char* str ) const;
 
private:
    // To check if the given char is number, if it is 
    // return its integer number, otherwise -1;
    int IsNumber( const char& aChar ) const;
 
private:
    char* iString;
 
};
 
CDoubleSix::CDoubleSix()
    :iString( NULL )
{
}
 
CDoubleSix::~CDoubleSix()
{
    if( iString != NULL )
    {
    delete iString;
    }
}
 
int CDoubleSix::CanDividedBySix( const char* str ) const
{
    if( str == NULL )
    {
        return -1; //invalid input
    }
    if( *str == '-' ) 
    {
        str++;
    }
 
    char ch;
    int num = -1;
    int sum = 0;
    while(*str!='/0')
    {
        ch = *str;
        num = IsNumber(ch);
        if( num == -1 )
        {
            return -2; // string contain non-number character
        }
        sum = sum + num;
        if( sum%3 == 0 )
        {
            sum = 0;
        }
        str++;
    }
     
    if( num%2 == 0 && sum == 0 )
    {
        return 1; // this string can be divided by six
    }
    else
    {
        return 0; // this string can not be divided by six
    }
}
 
int CDoubleSix::IsNumber( const char& aChar ) const 
{
    int num = aChar - '0';
    if( num >=0 && num <= 9 )
        return num;
    else
        return -1;
}
 
int main()
{
    CDoubleSix* dSix = new CDoubleSix();
    char* str = "-126663333331212122121211212";
    int ret = dSix->CanDividedBySix( str );
    if( ret == 0 )
    {
        cout<<"String: " <<str<<"  Can not be divided by six!"<<endl;
    }
    if( ret == 1 )
    {
        cout<<"String: " <<str<<"  Can be divided by six!"<< endl;
    }
    else
    {
        cout<<"Invalid input!" << endl;
    }

delete dSix;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值