Finding a Specific Digit of a Number

16,116

Solution 1

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

just define the function intPower.

Solution 2

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.)

Solution 3

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

Solution 4

number = 123456789
n = 5

tmp1 = (int)(number / 10^n);   // tmp1 = 12345
tmp2 = ((int)(tmp1/10))*10;    // tmp2 = 12340
digit = tmp1 - tmp2;           // digit = 5

Solution 5

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

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

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

Share:
16,116
Maxpm
Author by

Maxpm

/* No comment. */

Updated on July 28, 2022

Comments

  • Maxpm
    Maxpm almost 2 years

    I'm trying to find the nth 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?

  • Maxpm
    Maxpm over 13 years
    I can't convert number to a string to use .at(n), though. itoa isn't standard.
  • Cheers and hth. - Alf
    Cheers and hth. - Alf over 8 years
    Note that ^ is bitlevel XOR in C++.
  • c z
    c z over 2 years
    Need to handle out of bounds.