Return the nth digit of a number [closed]

元气小坏坏 提交于 2019-11-28 12:53:54

Without spoon-feeding you the code:

The nth digit is (the remainder of dividing by 10n) divided by 10n-1


If you wanted an iterative approach:

Loop n times, each time assigning to the number variable the result of dividing the number by 10.
After the loop, the nth digit is the remainder of dividing the number by 10.

--

FYI The remainder operator is %, so eg 32 % 10 = 2, and integer division drops remainders.

Arun Chandrasekhara Pillai
static int dig(int a, int b) {
    int i, digit=1;
    for(i=b-1; i>0; i++)
        digit = digit*10;
    digit = (a/digit) % 10;
    return digit;
 }

The other way is convert the digit into array and return the nth index

static char digit(int a,int b)
    {
        String x=a+"";
        char x1[]=x.toCharArray();
        int length=x1.length;
        char result=x1[length-b];
        return result;
    }

Now run from your main method like this way

System.out.println("digit answer  "+digit(1254,3));

output

digit answer  2

Convert number to string and then use the charAt() method.

class X{   
    static char digit(int a,int n)
    {
        String x=a+"";
        return x.charAt(n-1); 
    }

    public static void main(String[] args) {
        System.out.println(X.digit(123, 2));
    }
}

You may want to double check that the nth position is within the length of the number:

static char digit(int a, int n) {
    String x = a + "";
    char digit='\0' ;
    if (n > 0 && n <= x.length()) {
        digit = x.charAt(n - 1);
    }
    return digit;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!