1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
|
long sumDigits_v1(const long &sumMe)
{
char* numToCharList = new char[1000];//to know how many zeros to divide by multiple of 10... so 1331 becomes: {'1','3','3','1'}
long divisorList[10] = {1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000};//get char len via strlen to know which divisor to use
itoa(sumMe, numToCharList, 10);
long curDivisorIndx = strlen(numToCharList) - 1;
long curNumToCharListIndx = 0;
long sum = 0;
for ( long i = curDivisorIndx, j = curNumToCharListIndx;
i >= 0;
sum = sum + atol(&numToCharList[j])/divisorList[i],
--i, ++j);
delete[] numToCharList;
return sum;
}
|