/**
* 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
*/