You can also avoid converting to a string using the log10 function, int cmath, which returns the logarithm of the 10th base of the number (approximately its length if it were a string):
unsigned int getIntLength(int x) { if ( x == 0 ) return 1; else return std::log10( std::abs( x ) ) +1; } char getCharFromInt(int n, int x) { char toret = 0; x = std::abs( x ); n = getIntLength( x ) - n -1; for(; n >= 0; --n) { toret = x % 10; x /= 10; } return '0' + toret; }
I tested it and worked great (negative numbers are a special case). In addition, it is necessary to consider that in order to find the nth element, you need to "go back" in the loop, subtracting the int from the total length.
Hope this helps.
Baltasarq
source share