From Cay Horstmann's "C++ For Everyone" Chapter 4: Loops
Write a program that adds up the sum of all odd digits of n. (For example, if n is 32677, the sum would be 3 + 7 + 7 = 17)
I don't know how to make the computer "see" the numbers like separate them
CodeChef discussion forum allows programmers to discuss solutions and problems regarding C Programming Tutorials and other programming issues.
n % 10
gets the value of the one's digit. You can figure it out from there right?
Here's a hint. C++ has the modulus operator %
. It will produce the remainder when two numbers are divided together. So if I wanted to know the last digit in a number which was greater than 10 I would modulus 10 and get the result
int lastDigit = number % 10;
The last digit of a base-10 integer i
is equal to i % 10
. (For reference, %
is the modulus operator; it basically returns the remainder from dividing the left number by the right.)
So, now you have the last digit. Once you do, add it to a running total you're keeping, divide i
by 10 (effectively shifting the digits down by one place), or in your case 100 (two places), and start back at the beginning. Repeat until i == 0
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With