Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the Nth digit of an integer with bit-wise operations?

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.

like image 693
John Smith Avatar asked Oct 15 '08 06:10

John Smith


People also ask

How do you set a bit in an nth position?

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.


1 Answers

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.

like image 142
Greg Hewgill Avatar answered Oct 04 '22 00:10

Greg Hewgill