Question

I just wanted to write a minimalistic program in C to calculate the sum of digits of some natural number (the sum of digits is defined as follows: sumOfDigits(123) = 6, sumOfDigits(0) = 0, sumOfDigits(32013) = 9, and so on).

So far, everything is ok with the following code snippet. For example, for 5100 it delivers 6, correctly. But, why is 14 delivered for 05100 (remember the leading 0)?

What's going on here?

I had a look at the binary representation of the numbers, but that didn't give any information to me. (BTW: The following code should run anywhere, I guess.)

#include <stdio.h>

unsigned int sumOfDigits(unsigned int n) {
    int retval = 0;
    while (n > 0) {
        retval += n % 10;
        n/=10;
    }
    return retval;
}

int main() {
    printf("OK: %u\n", sumOfDigits(5100u));
    printf("WTF: %u",  sumOfDigits(05100u));
    return 0;
}

EDIT: As Zaibis stated .... a leading 0 means octal notation. :-) and so: 5100_8 == 2624_10

Was it helpful?

Solution

A leading 0 means you want to use octal digit system.

So 017 i.e. would be decimal: 15

And your 05100 would be decimal: 2624

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top