and the sum of its digits is
What is the sum of the digits of the number ?
With the big integer type IntX (which I added to my project to solve an earlier problem) this one is pretty much as easy as you’d think.
.Select(x => x - '0')
It first does the calculation and then gets the string representation of the result. And in case you were wondering, that would be:
And as a comparison, here is the largest number that can be represented using built-in .net types.
As you can see, the first number is kind of bigger than the second 😛 Aaaanyways, the next bit might be a bit cryptic. But fear not, it is actually quite simple:
- A string is an array of characters.
- All characters have a character code (a numeric value).
- The character codes for the numeric characters (‘0’, ‘1’, and so on) comes after each other, which means that for example ‘1’ has a character code value which is 1 larger than the character code of ‘0’.
- If we take a character code and subtracts it from itself, we get zero. (Thank you captain obvious…)
- This means that if we subtract ‘0’ from ‘0’, we get 0. And if we subtract ‘0’ from ‘5’, we get 5. (Oh, right, clever!)
So, the last two lines in my code simply converts all the characters in the string into actual numbers and then sums them together. Which would get us the answer! Tadaa ^_^
How did you do? Have you found a more interesting solution? Please do share 🙂