Computer Science Canada

Use only a certain digit in a number

Author:  uberwalla [ Thu Feb 21, 2008 4:41 pm ]
Post subject:  Use only a certain digit in a number

hey there quick question. This say i am given a number "12345", how would i go about just getting one digit out of that? so that i could pull all the numbers out and go 1+2+3+4+5+6 and stuff like that

Author:  HeavenAgain [ Thu Feb 21, 2008 4:48 pm ]
Post subject:  RE:Use only a certain digit in a number

if its a string, then its fairly easy
code:
for (int i = 0 ; i < number.length(); i++)
  sum += Character.getNumericValue(number.charAt(i));

if its not a string, then you can just go
code:
while (temp>0){
 digit = temp%10;
 temp /= 10;
}

Author:  OneOffDriveByPoster [ Thu Feb 21, 2008 4:53 pm ]
Post subject:  Re: Use only a certain digit in a number

uberwalla @ Thu Feb 21, 2008 4:41 pm wrote:
hey there quick question. This say i am given a number "12345", how would i go about just getting one digit out of that? so that i could pull all the numbers out and go 1+2+3+4+5+6 and stuff like that
The % operator gives you the remainder after division with /. Remember that 12345 = 1 * 10000 + 2 * 1000 + 3 * 100 + 4 * 10 + 5 * 1.

Author:  uberwalla [ Thu Feb 21, 2008 5:27 pm ]
Post subject:  Re: Use only a certain digit in a number

works pretty well thanks guys


: