I recently had a test in my class. One of the problems was the following:
Given a number n, write a function in C/C++ that returns the sum of the digits of the number squared. (The following is important). The range of n is [ -(10^7), 10^7 ]. Example: If n = 123, your function should return 14 (1^2 + 2^2 + 3^2 = 14).
This is the function that I wrote:
int sum_of_digits_squared(int n)
{
int s = 0, c;
while (n) {
c = n % 10;
s += (c * c);
n /= 10;
}
return s;
}
Looked right to me. So now the test came back and I found that the teacher didn’t give me all the points for a reason that I do not understand. According to him, for my function to be complete, I should’ve have added the following detail:
int sum_of_digits_squared(int n)
{
int s = 0, c;
if (n == 0) { //
return 0; //
} //
// THIS APPARENTLY SHOULD'VE
if (n < 0) { // BEEN IN THE FUNCTION FOR IT
n = n * (-1); // TO BE CORRECT
} //
while (n) {
c = n % 10;
s += (c * c);
n /= 10;
}
return s;
}
The argument for this is that the number n is in the range [-(10^7), 10^7], so it can be a negative number. But I don’t see where my own version of the function fails. If I understand correctly, the meaning of while(n)
is while(n != 0)
, not while (n > 0)
, so in my version of the function the number n wouldn’t fail to enter the loop. It would work just the same.
Then, I tried both versions of the function on my computer at home and I got exactly the same answers for all the examples that I tried. So, sum_of_digits_squared(-123)
is equal to sum_of_digits_squared(123)
(which again, is equal to 14
) (even without the detail that I apparently should’ve added). Indeed, if I try to print on the screen the digits of the number (from least to greatest in importance), in the 123
case I get 3 2 1
and in the -123
case I get -3 -2 -1
(which is actually kind of interesting). But in this problem it wouldn’t matter since we square the digits.
So, who’s wrong?
EDIT: My bad, I forgot to specify and didn’t know it was important. The version of C used in our class and tests has to be C99 or newer. So I guess (by reading the comments) that my version would get the correct answer in any way.