I'm trying to find the n
th digit of an integer of an arbitrary length. I was going to convert the integer to a string and use the character at index n...
char Digit = itoa(Number).at(n);
...But then I realized the itoa
function isn't standard. Is there any other way to do this?
Itoa is in stdlib.h.
You can also use an alternative itoa:
Alternative to itoa() for converting integer to string C++?
or
ANSI C, integer to string without variadic functions
Assuming
number.at(n)
returns a decimal digit in the range 0...9, that is.You can also use the % operator and / for integer division in a loop. (Given integer n >= 0, n % 10 gives the units digit, and n / 10 chops off the units digit.)
It is also possible to avoid conversion to string by means of the function log10, int cmath, which returns the 10th-base logarithm of a number (roughly its length if it were a string):
I have tested it, and works perfectly well (negative numbers are a special case). Also, it must be taken into account that, in order to find tthe nth element, you have to "walk" backwards in the loop, subtracting from the total int length.
Hope this helps.
You can use ostringstream to convert to a text string, but a function along the lines of:
should do the trick with a lot less complications. (For starters, it handles the case where n is greater than the number of digits correctly.)
-- James Kanze
A more general approach:
Just lets you do the same thing for different base numbers (e.g. 16, 32, 64, etc.).