Textrus
Textrus

Reputation: 11

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? One for the number, and the other for the index and will return the value at index...

Upvotes: 1

Views: 930

Answers (2)

User253489
User253489

Reputation: 189

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

Upvotes: 0

Ulysse BN
Ulysse BN

Reputation: 11396

You could do it using the charAt() method for a string:

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

You could ensure the pos number is in range before looking for it:

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

Upvotes: 3

Related Questions