Computer Science Canada

Separate a Number's Digits

Author:  rar [ Thu Nov 05, 2009 2:10 pm ]
Post subject:  Separate a Number's Digits

In a test preparation exercise I just received, one question poses the problem of
If you are given a number, (ex. 13.23), print the sum of the number's digits.

So in this case, 1 + 3 + 2 + 3 = 9

Sample Input:
12.45
Sample Output:
12
(meaning 1 + 2 + 4 + 5 = 12)

Author:  Tony [ Thu Nov 05, 2009 2:45 pm ]
Post subject:  RE:Separate a Number\'s Digits

Was there a question that you had about that?

Author:  rar [ Thu Nov 05, 2009 2:51 pm ]
Post subject:  RE:Separate a Number\'s Digits

Nope, just letting you know!

Author:  rar [ Thu Nov 05, 2009 2:54 pm ]
Post subject:  RE:Separate a Number\'s Digits

Sorry, I had to say it lol...I found my own idiocy amusing lol so I apologize.

My question was definitely:

How would you go about doing this in C?

Author:  Tony [ Thu Nov 05, 2009 3:01 pm ]
Post subject:  RE:Separate a Number\'s Digits

Same way as in any other language. Division by powers of 10.

Author:  Insectoid [ Thu Nov 05, 2009 3:06 pm ]
Post subject:  RE:Separate a Number\'s Digits

Another very messy way would be to convert the number to a string, take the first character, convert it to an integer. Do the same for the 2nd digit and add them. Repeat with the 3rd, and so on. This would be very slow though. Tony's way would be faster, cleaner, and all around a better solution. I would do it recursively.

Author:  Tony [ Thu Nov 05, 2009 3:10 pm ]
Post subject:  Re: RE:Separate a Number\'s Digits

insectoid @ Thu Nov 05, 2009 3:06 pm wrote:
convert the number to a string...

That would also defeat the purpose of the exercise.

Author:  rar [ Thu Nov 05, 2009 6:37 pm ]
Post subject:  RE:Separate a Number\'s Digits

ok so...can you be more specific???

Author:  Tony [ Thu Nov 05, 2009 6:42 pm ]
Post subject:  RE:Separate a Number\'s Digits

Do it on paper first, it's all math anyway.

Hint: you can shift numbers left/right with powers of 10.

12.34 * 10 = 123.4
12.34 / 10 = 1.234

Author:  rar [ Thu Nov 05, 2009 10:42 pm ]
Post subject:  RE:Separate a Number\'s Digits

Right but then how would you get the later digits by themselves to add them?

Author:  Tony [ Thu Nov 05, 2009 11:04 pm ]
Post subject:  RE:Separate a Number\'s Digits

code:

(int)1.234 == 1

Author:  rar [ Fri Nov 06, 2009 10:46 am ]
Post subject:  RE:Separate a Number\'s Digits

yes...so then would you go get rid of the one, multiply by 10 accordingly, and then cast the second digit in the same way?

Author:  OneOffDriveByPoster [ Fri Nov 06, 2009 6:12 pm ]
Post subject:  Re: Separate a Number's Digits

Well, in general, you have to handle the digits in the non-fractional part too. You may want to consider division there.


: