Computer Science Canada

Addition of Digits in integer

Author:  Caceres [ Wed Jul 12, 2006 10:42 pm ]
Post subject:  Addition of Digits in integer

Hello, I was just wondeirng how to add the digits of an integer.

For example:

code:

private static int sumofbinumbers(String sin) {
two=(sin.charAt(1)-48)*2
four=(sin.charAt(3)-48)*2
six=(sin.charAt(5)-48)*2
eight=(sin.charAt(7)-48)*2
               
sum_two=(two.charAt(0)) + (two.charAt(1))
sum_four=(four.charAt(0)) + (four.charAt(1))
sum_six=(six.charAt(0)) + (six.charAt(1))
sum_eight=(eight.charAt(0)) + (eight.charAt(1))


I'm basically curious into how to add up the sums of digits of an integer.
I wa wondering if the sum_two and the part to follow will work.
Would i have to put int two = (sin.charAt(1)-48)*2.
Thanks.
P.S Sorry if this is unclear
~Caceres

Author:  wtd [ Wed Jul 12, 2006 11:30 pm ]
Post subject: 

There's a mathematical way of doing this. Since I don't like just giving out easy answers...

code:
(define (sum-digits n)
  (if (= n 0)
      0
      (+ (remainder n 10)
         (sum-digits (floor (/ n 10))))))

Author:  Caceres [ Thu Jul 13, 2006 10:13 pm ]
Post subject: 

For my previous code. It keeps saying
Quote:
int cannot be dereference

Anyone know what this means?

Author:  Caceres [ Thu Jul 13, 2006 10:28 pm ]
Post subject: 

For my previous code. It keeps saying
Quote:
int cannot be dereference

Anyone know what this means?

Author:  [Gandalf] [ Thu Jul 13, 2006 11:00 pm ]
Post subject: 

It means that an int is not an object, and therefore cannot be treated as such. An Integer, however...


: