Finding a Specific Digit of a Number

后端 未结 9 1887
深忆病人
深忆病人 2020-12-16 23:32

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

9条回答
  •  温柔的废话
    2020-12-16 23:56

    It is also possible to avoid conversion to string by means of the function log10, int cmath, which returns the 10th-base logarithm of a number (roughly 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 have tested it, and works perfectly well (negative numbers are a special case). Also, it must be taken into account that, in order to find tthe nth element, you have to "walk" backwards in the loop, subtracting from the total int length.

    Hope this helps.

提交回复
热议问题