Return the nth digit of a number [closed]

梦想与她 提交于 2019-11-26 21:57:04

问题


public class Return {    
    public static void main(String[] args) {        
        int answer = digit(9635, 1);
        print("The answer is " + answer);
    }

    static void print(String karen) {
        System.out.println (karen);
    }

    static int digit(int a, int b) {
        int digit = a;
        return digit;
    }     
}

Create a program that uses a function called digit which returns the value of the nth digit from the right of an integer argument. The value of n should be a second argument.

For Example: digit(9635, 1) returns 5 and digit(9635, 3) returns 6.


回答1:


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.




回答2:


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;
 }



回答3:


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



回答4:


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;
}


来源:https://stackoverflow.com/questions/19194257/return-the-nth-digit-of-a-number

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!