
-----------------------------------
iluvchairs112
Thu Jun 14, 2007 6:27 am

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

-----------------------------------
Dan
Thu Jun 14, 2007 6:47 am

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.

-----------------------------------
HeavenAgain
Thu Jun 14, 2007 9:50 am

Re: print sum
-----------------------------------
for converting an int to a string you can simply use 

Integer.toString(INT,int)
OR
Integer.toString(INT)

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

Integer.valueOf(string)


and for some other useful code you can use are

"123".length()

"123".charAt(1)


i hope this helps  :P

-----------------------------------
richcash
Thu Jun 14, 2007 8:54 pm

Re: print sum
-----------------------------------
int num = 32781;
int sum = 0;
for (int i = 0; i < 5; i ++) {
	sum += (int) (num / Math.pow(10, i)) % 10;
}
System.out.println(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.

-----------------------------------
rizzix
Thu Jun 14, 2007 11:58 pm

RE:print sum
-----------------------------------
Just to demonstrate Scala Views (and implicit anonymous functions)... 

class IterableInt(val num : Int) extends Iterator
    
Console print (456).foldRight(0) { _ + _ } // 15
