noob question: easiest way to parse an int?

M

Martin Gregorie

Tim said:
user said:
say i got an int, 530: what could i do to get back 2nd digit [the 3 in
this case]?

If N is the variable with the int, and you are counting from the right, then
you could try this:

(N/10)%10

Similarly, (N/100)%10 would be the 5, and (N/1)%10 would be the 0.

Thats asking to be generalized as:

/**
* Return the nth digit from value. Digits are counted from the right.
* The rightmost digit is zero. -1 is returned of n doesn't reference
* a digit within the number.
*/
int getDigit(int value, int n)
{
int i = 1;
int digit = -1;

value = Maths.abs(value);
if (n >= 0)
{
while ((value/(10*i) > 0)
i++;

digit = (n >= i ? -1 : value/(10*n)%10);
}

return digit;
}

The absolute value is only required for the range test on n to work.
 
L

Lasse Reichstein Nielsen

{ final static int pot[] = new int[]
{ 1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000 };

public int secondDigitOf( final int number /* must be >= 10 */ )
{ int n = number; int l = 0;
if( n >= 100000000 ){ l += 8; n /= 100000000; }
if( n >= 10000 ){ l += 4; n /= 10000; }
if( n >= 100 ){ l += 2; n /= 100; }
if( n >= 10 ){ l += 1; n /= 10; }
return number / pot[ l - 1 ]% 10; }

Why the indirection through an array lookup, if efficiency is
important? You should get the same effect from:

public int secondDigitOf( final int number /* must be >= 10 */ ) {
int n = number;
int m = 1;
if ( n >= 100000000 ) { m *= 100000000; n /= 100000000; }
if ( n >= 10000 ) { m *= 10000; n /= 10000; }
if ( n >= 100 ) { m *= 100; n /= 100; }
if ( n >= 10 ) { m *= 10; n /= 10; }
return (number / (m/10)) % 10; }
}

/L
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,770
Messages
2,569,584
Members
45,075
Latest member
MakersCBDBloodSupport

Latest Threads

Top