'Finding Sum of Square of Digits Beginner Bug C++

So, I started learning C++ recently. This code is trying to add the sum of the squares of each numbers digits. For example: 243: 2*2 + 4*4 + 3*3 = 29.

int sumOfSquareDigits(int n) //BUG WITH INPUT OF 10, 100, 1000, etc.
{
    int digits = findDigits(n);
    int number;
    int remainder;
    int *allDigits = new int[digits];
    for (int i = 0; i < digits; i++) { //assigns digits to array
        if (i + 1 == digits){ //sees if there is a ones value left
            allDigits[i] = n;
        }
        else {
            remainder = (n % findPower10(digits - (i + 1)));
            number = ((n - remainder) / findPower10(digits - (i + 1)));
            allDigits[i] = number; //records leftmost digit
            n = n - (allDigits[i] * findPower10(digits - (i + 1))); //gets rid of leftmost number and starts over
        }
    }
    int result = 0;
    for (int i = 0; i < digits; i++) { //finds sum of squared digits
        result = result + (allDigits[i] * allDigits[i]);
    }
    delete [] allDigits;
    return result;
}

int findDigits(int n) //finds out how many digits the number has
{
int digits = 0;
int test;
    do {
        digits++;
        test = findPower10(digits);
    } while (n > test);
    return digits;
}

int findPower10(int n) { //function for calculating powers of 10
    int result = 1;
    for (int i = 0; i < n; i++)
        result = result * 10;
    return result;
}

And after running the code, I've figured out that it (barely) mostly works. I've found that whenever a user inputs a value of 10, 100, 1000, etc. it always returns a value of 100. I'd like to solve this only using the iostream header.

Sorry if my code isn't too readable or organized! It would also be helpful if there are any shortcuts to my super long code, thanks!

c++


Solution 1:[1]

I found the problem challenging managed to reduce your code to the following lines:

long long sumOfSquareDigits(long long i) {  
  long long sum(0L);
  do {
    long long r = i % 10;
    sum += (r * r);    
  } while(i /= 10);

  return sum;
}

Haven't test it thoroughly but I think it works OK.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1