Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Simple Java stuff. :X
#4
mrcowcow Wrote:In my first method, I have to pass an integer into a method, and use the method to find the sum of the digits. I have no idea in hell how I'm supposed to even start doing this. :X

There are (at least) two ways of doing this:

Turn the integer into a string, then go through each character in the string, and sum them up through convertion.

Or think this way:
let us call the function we're naming for f, with input int x. If x = 0, then return 0, otherwise, return the "tenth" plus f((x - tenth)/10).

This can be written as this: (I assume you know discrete mathematics?)
Code:
//Pseudo. I'll not doing your homework, think for yerself! :D
f (x) {
   if (x == 0)
     return 0
   else {
     y = x % 10
     z = f((x - y)/10)
     return(y + z)
   }
}

Eventually, the code can be optimized extremely, but this is the initial theory behind.
Reply


Messages In This Thread
Simple Java stuff. :X - by mrcowcow - 2009-12-13, 09:35 PM
Simple Java stuff. :X - by JoeTang - 2009-12-13, 09:38 PM
Simple Java stuff. :X - by mrcowcow - 2009-12-13, 09:43 PM
Simple Java stuff. :X - by Nikkey - 2009-12-13, 09:52 PM
Simple Java stuff. :X - by mrcowcow - 2009-12-13, 10:01 PM

Forum Jump:


Users browsing this thread: 1 Guest(s)