Search for a specific number digit

I am trying to find the nth bit of an integer of arbitrary length. I was going to convert an integer to a string and use the character in index n ...

char Digit = itoa(Number).at(n);

... But then I realized that the itoa function is not standard. Is there any other way to do this?

+8
c ++ integer digit
source share
9 answers

(number/intPower(10, n))%10

just define the intPower function.

+17
source share

You can also use the% and / operator for integer division in a loop. (For a given number n> = 0, n% 10 gives the number of units, and n / 10 discards the number of units.)

+3
source share

Itoa is located in stdlib.h.

You can also use the itoa alternative:
Alternative to itoa () to convert integer to C ++ string?
or
ANSI C, an integer per line without variational functions

+1
source share
 number = 123456789 n = 5 tmp1 = (int)(number / 10^n); // tmp1 = 12345 tmp2 = ((int)(tmp1/10))*10; // tmp2 = 12340 digit = tmp1 - tmp2; // digit = 5 
+1
source share

You can use ostringstream to convert to a text string, but the function along the lines:

 char nthDigit(unsigned v, int n) { while ( n > 0 ) { v /= 10; -- n; } return "0123456789"[v % 10]; } 

should do the trick with much less complications. (For a starter, it handles the case where n is greater than the number of digits correctly.)

- James Kanze

+1
source share

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.

+1
source share

Direct answer:

 char Digit = 48 + ((int)(Number/pow(10,N)) % 10 ); 

You must include the <math> library

+1
source share
 const char digit = '0' + number.at(n); 

Assuming number.at(n) returns a decimal digit in the range 0 ... 9, that is.

0
source share

A more general approach:

 template<int base> int nth_digit(int value, int digit) { return (value / (int)pow((double)base, digit)) % base; } 

It just allows you to do the same for different base numbers (e.g. 16, 32, 64, etc.).

0
source share

Source: https://habr.com/ru/post/650026/


All Articles