How to get the Nth digit of a number in Java

2 Answers

0 votes
public class MyClass {
    public static void main(String args[]) {
        int number = 873591;
        String s = String.valueOf(number);
        int N = 4;
        
        char ch = s.charAt(N - 1);
        System.out.println(ch);
        
        int x = s.charAt(N - 1) - '0';
        System.out.println(x);
    }
}



/*
run:

5
5

*/

 



answered Jun 1, 2020 by avibootz
0 votes
/**
 * Utility class for digit-related operations.
 */
public final class NumberUtils {

    private NumberUtils() {
        // Prevent instantiation of utility class.
    }

    /**
     * Returns the N-th digit of a number, counting from the left.
     *
     * Examples:
     * number = 12745
     * position = 1 -> 1
     * position = 3 -> 7
     *
     * @param number   The input number.
     * @param position The digit position (1-based, from the left).
     * @return The digit at the specified position.
     * @throws IllegalArgumentException If position is out of range.
     */
    public static int getDigitFromLeft(long number, int position) {
        String digits = Long.toString(Math.abs(number));
    
        if (position < 1 || position > digits.length()) {
            throw new IllegalArgumentException(
                "Position is out of range."
            );
        }
    
        return digits.charAt(position - 1) - '0';
    }

    public static void main(String[] args) {
        long number = 12745;

        System.out.println(getDigitFromLeft(number, 1)); 
        System.out.println(getDigitFromLeft(number, 3)); 
        System.out.println(getDigitFromLeft(number, 5)); 
    }
}



/*
run:

1
7
5

*/

 



answered 1 day ago by avibootz
...