Example. 123456, and we want the third from the right ('4') out.
The idea in practise is to access each digit seperately (ie. 6 5 4 3 2 1).
C/C++/C# preferred.
Given a number n and a value k. From the right, set the kth bit in the binary representation of n. The position of LSB(or last bit) is 0, second last bit is 1 and so on. Also, 0 <= k < x, where x is the number of bits in the binary representation of n.
A more efficient implementation might be something like this:
char nthdigit(int x, int n) { while (n--) { x /= 10; } return (x % 10) + '0'; }
This saves the effort of converting all digits to string format if you only want one of them. And, you don't have to allocate space for the converted string.
If speed is a concern, you could precalculate an array of powers of 10 and use n to index into this array:
char nthdigit(int x, int n) { static int powersof10[] = {1, 10, 100, 1000, ...}; return ((x / powersof10[n]) % 10) + '0'; }
As mentioned by others, this is as close as you are going to get to bitwise operations for base 10.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With