Get the last digit of a number

How can I get the last digit of an int?
Apply %10 to it.
Thanks
Wouldn't 10% only work if the int was less than 100? I was thinking that you could probably convert the int to a char array and just grab the last character in the array. I'm relatively new to c++ so take what I say with a grain of salt but what I'm suggesting sounds more accurate.

Something like

Char Last[sizeof(int)]="" + int + ""
Char Result[1]=Last[sizeof(int)-1]

Probably not syntax error free but I'd imagine something like this would probably work.
Last edited on
No? N % (something greater than N) will always simply return N.
Last edited on
Wouldn't 10% only work if the int was less than 100?

It's % 10 (not 10 %), and it works for any size number.
It returns the remainder you would get after dividing the number by 10.
Last edited on
I'm relatively new to c++ so take what I say with a grain of salt but what I'm suggesting sounds more accurate.

this isnt really c++ here. Its math. what is 123456 % 10?
123456 / 10 is 12345. the remainder = 6. ...
but what is 0xABCD % 0xF? Do you see it? (D).

there are times when processing a char array from a number is more efficient. Depends on what you are doing, so your idea has value for many problems.
Last edited on
Very interesting. Clearly I'm not that familiar with the % operator. I'm pretty good at math. Never had a reason to use % in this manner. But I guess you learn something everyday. That's why I came here. Lol I may never use it again in life but good to know.
markyrocks wrote:
Never had a reason to use % in this manner. But I guess you learn something everyday.

In what manner have you used it? This is raw beginner stuff.
Last edited on
The most common uses of % have faded behind all our containers and tools; the only thing I can think of off the top of my head that uses % in a practical example would be a circular buffer. Im sure others have ideas on that, but you will see it again.
markyrocks wrote:
Clearly I'm not that familiar with the % operator. Never had a reason to use % in this manner.

Echoing dutch:
What did you know about the modulo operator before today?
How have you used it?
use %10 to get the last digit of the number.
@jonnin,

0xABCD % 0xF is actually 1.

You meant 0xABCD % 0x10 = D.
jonnin was apparently thinking of (confusing it with) bitwise masking with &.
Clearly a brain fart since he obviously knows the difference!
But using & 0xF would actually be more efficient/appropriate in the hexadecimal case.
Sigh. Sorry about that … I hate when I do that
Topic archived. No new replies allowed.