Getting the units of a number

A

Adrian Gibbons

Hello,

I need to get the units of a number.

i.e. if I had 12345 then I would want '5'.

I was looking at dividing the number by ten and using the modulus
operator repeatedly until I had only the units, but wondered if there
was an easier way?

Regards,

Adrian.
 
P

Peter van Merkerk

I need to get the units of a number.
i.e. if I had 12345 then I would want '5'.

I was looking at dividing the number by ten and using the modulus
operator repeatedly until I had only the units, but wondered if there
was an easier way?

The loop could do without the modulus operator:

int number = ....
int units = 0;
while(number)
{
units++;
number/=10;
}

One other way to do it would be to use log10():

int units = log10(number) + 1; // number must be > 0
 
A

Artie Gold

Adrian said:
Hello,

I need to get the units of a number.

i.e. if I had 12345 then I would want '5'.

I was looking at dividing the number by ten and using the modulus
operator repeatedly until I had only the units, but wondered if there
was an easier way?
Erm, why are you working so hard? ;-(

int get_units( int n ) {
return n % 10;
}

HTH,
--ag
 
K

Kevin Saff

Adrian Gibbons said:
Hello,

I need to get the units of a number.

i.e. if I had 12345 then I would want '5'.

I was looking at dividing the number by ten and using the modulus
operator repeatedly until I had only the units, but wondered if there
was an easier way?

You do know that any integer mod 10 is the units part (12345 % 10 == 5)
don't you? Or did you mean the number of digits in the integer?
 
D

David Rubin

This is the number of digits, rather than the numeral in the "ones" place...

[snip]
int number = ....
int units = 0;
while(number)
{
units++;
number/=10;
}

You want to initialize units to 1 or use a do/while loop. Otherwise, the
number 0 has 0 units...

/david
 

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
474,145
Messages
2,570,826
Members
47,371
Latest member
Brkaa

Latest Threads

Top