简体   繁体   English

找到数字的第n位数

[英]Find the n-th Digit of a Number

I know that 2389 % 10 is 9, but how could I create a method that takes 2 parameters? 我知道2389%10是9,但我怎么能创建一个带2个参数的方法呢? One for the number, and the other for the index and will return the value at index... 一个用于数字,另一个用于索引,并将返回索引处的值...

You could do it using the charAt() method for a string: 您可以使用charAt()方法为字符串执行此操作:

public static int getNthDigit(int n, int pos) {
    return Character.getNumericValue(String.valueOf(n).charAt(pos))
}

Be careful : index start from 0. That means getNthDigit(1234,2) will return 3 注意 :index从0开始。这意味着getNthDigit(1234,2)将返回3

You could ensure the pos number is in range before looking for it: 在查找之前,您可以确保pos号在范围内:

public static int getNthDigit(int n, int pos) {
    String toStr = String.valueOf(n)
    if (pos >= toStr.length() || pos < 0) {
        System.err.println("Bad index")
        return -1
    }
    return Character.getNumericValue(toStr.charAt(pos))
}
public static int getDigitAtIndex(int numberToExamine, int index) {
        if(index < 0) {
            throw new IndexOutOfBoundsException();
        }
        if(index == 0 && numberToExamine < 0) {
            throw new IllegalArgumentException();
        }
        String stringVersion = String.valueOf(numberToExamine);
        if(index >= stringVersion.length()) {
            throw new IndexOutOfBoundsException();
        }
        return Character.getNumericValue(stringVersion.charAt(index));
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM