troubleshooting my code. nth digit of integer.

library is about to close and don't have time right now.
its really stumping me however as I went over and over this code in my mind as I actually wrote it out on paper and my gut tells me it should work.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32

very long get_int_size(very long n)
{//I think this is for positive ints only
    very long counter = 1, divisor = 1;
    while( (counter++) && (divisor *= 10) )
        if ((n/divisor) >= 1)
            continue;
        else break;
    return counter-1;
}

int nth_digit(int n, int d)
{
    int tn = n;
    if (tn<0)
        tn *= -1;  //do I need this?
    int s = get_int_size(tn);
    if (d > s || d < 1)
        return -1;
    int increment = 1,place_holder = 10, counter = 0;
    for (int i = 1; i < d; ++i)
        {
            tn = tn - (increment * nth_digit(tn, i));
            place_holder *= 10;
            increment *=10;
        }
    do
        if (tn % place_holder == 0)
            return ((place_holder - (counter*increment)) %place_holder )/increment;
        while(tn +=increment && counter++ && tn <= (n + place_holder));
    return -2;
}


Thanks
closed account (DSLq5Di1)
That looks overly complicated, a simple loop dividing your integer by 10 (n) times will do, then use modulo operator to return the remainder of that value divided by 10.
You don't understand. I need to get the nth digit of the number n where d is the place of the digit I want to get.

P. S. I fixed it.

changed line 5 and 30 from counter++ post-increment to ++counter pre-increment and also changed line 4 from 1, 1 to 0, 1 respectively.

I suppose yours would work too though, thanks.

Thanks.

P.P.S.

Mine would win a code obfuscation contest? A newbie programmer code obfuscation contest that is.
Last edited on
Topic archived. No new replies allowed.