有一个数字串,他的长度超出最长整形的处理范围,请确定该数串是否能够被六整除。
源码如下,请大家批评指正。
#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;
}