Computer Science Canada print sum |
Author: | iluvchairs112 [ Thu Jun 14, 2007 6:27 am ] |
Post subject: | print sum |
how would I go about finding the sum of every digit in an integer? i can't figure out how to get the digits to be separated |
Author: | Dan [ Thu Jun 14, 2007 6:47 am ] |
Post subject: | RE:print sum |
The easiest way would be to cover the integer into a string and then make a loop for the length of the string that goses to each char in it coverts it back to a number and then adds it to a total. |
Author: | HeavenAgain [ Thu Jun 14, 2007 9:50 am ] | ||||||
Post subject: | Re: print sum | ||||||
for converting an int to a string you can simply use
where INT is the integer you want to convert, and int is the number system, 2 for binary, 16 for hex, etc and for the converting back part, you can use
and for some other useful code you can use are
i hope this helps ![]() |
Author: | richcash [ Thu Jun 14, 2007 8:54 pm ] | ||
Post subject: | Re: print sum | ||
Go through that step-by-step. If I want the 4th digit from the left, then it divides by 10^3 (which leaves 32.781). Then I round it down to 32 and mod by 10 (which leaves 2). See how simple it is, when you mod an integer by 10, it will give you the number in the ones column, you don't even have to understand modulus. But in the above code we have to put the length of the integer ourselves. If you don't want to do this, then take the log (base 10) of the number, round down, and add 1. That will give you the length of the integer. |
Author: | rizzix [ Thu Jun 14, 2007 11:58 pm ] | ||||
Post subject: | RE:print sum | ||||
Just to demonstrate Scala Views (and implicit anonymous functions)...
|