Find First Digit in Java
Problem
The first digit of a number is whatever remains once every digit after it has been divided away — dividing by 10 repeatedly strips digits from the right until only the leading one is left.
Given a number, find its first (leftmost) digit.
Java Program
public class FirstDigit {
public static void main(String[] args) {
int n = 45678;
while (n >= 10) { // keep dividing until only one digit remains
n /= 10;
}
System.out.println("First digit: " + n);
}
}Output
Core Logic
Dividing the number by 10 for as long as it's 10 or greater strips away every digit except the leading one, since a single-digit value can't be divided down any further without losing it.
- 1The loop condition
n >= 10keeps dividing as long as more than one digit remains. - 2Each pass divides
nby10, discarding the last digit. - 3Once
ndrops below10, only the original first digit is left.
45678, dividing by 10 four times strips off 8, 7, 6, and 5 in turn, leaving 4.Key Point: The loop stops at n < 10 rather than n > 0 — dividing all the way down to zero would lose the first digit instead of isolating it.
Why: The loop strips one trailing digit per iteration until only the leading digit of the original d-digit number remains.
Key Concepts
Approach 2: Using String charAt(0)
public class FirstDigitCharAt {
public static void main(String[] args) {
int n = 45678;
// Reads the first character of the digit string and converts it back to a digit
int firstDigit = String.valueOf(n).charAt(0) - '0';
System.out.println("First digit: " + firstDigit);
}
}
Output
Core Logic
Converting the number to a String and reading its first character gives the leading digit directly, without a manual division loop.
- 1
String.valueOf(n)converts the number into its digit string. - 2
.charAt(0)reads the first character of that string, which is the leading digit. - 3
- '0'converts that character back into its numeric digit value.
45678, String.valueOf(45678).charAt(0) is '4', and subtracting '0' gives the numeric digit 4.Key Point: Building the digit string still costs work proportional to the digit count, even though only the first character ends up being read.
Why: Converting the number to a String still does work proportional to its digit count d, even though only the first character is read afterward.