In this article, we are going to find first and last digit of a number.
To find first and last digit of any number, we can have several ways like using modulo operator or pow() and log()
methods of Math
class etc.
Table of Contents
Before moving to example, let’s first create an algorithm to find first and last digit of a number.
Algorithm
Step 1:
Take a number from the user.
Step 2:
Create two variables firstDigit
and lastDigit
and initialize them by 0.
Step 3:
Use modulo operator(%
) to find last digit.
Step 4:
Use either while loop and division operator (/
) or log()
and pow()
methods of Math
class to find
.
Step 5:
Display the result.
Using while loop
It is easy to use modulo operator that will return the last digit of the number, and we can use while loop and division operator to get first digit of number.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
public class Main { public static void main(String args[]) { int number = 502356997; int firstDigit = 0; int lastDigit = 0; lastDigit = number%10; System.out.println("Last digit: "+lastDigit); while(number!=0) { firstDigit = number%10; number /= 10; } System.out.println("First digit: "+firstDigit); } } |
Output
First digit: 5
Using log() and pow() methods
If we want to use built-in methods
like log() and pow() of Math class, then we can use log()
method to get the number of digits and pow()
method to get divisor value that later on used to get the first digit of number. See the example below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
public class Main { public static void main(String args[]) { int number = 502356997; int firstDigit = 0; int lastDigit = 0; // find last digit lastDigit = number%10; System.out.println("Last digit: "+lastDigit); int digits = (int)(Math.log10(number)); // Find first digit firstDigit = (int)(number / (int)(Math.pow(10, digits))); System.out.println("First digit: "+firstDigit); } } |
Output
First digit: 5
Using while loop and pow() method
If we don’t want to use log()
method then use while loop to count the number of digits and use that count into the pow() method to get divisor. See the example below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
public class Main { public static void main(String args[]) { int number = 502356997; int firstDigit = 0; int lastDigit = 0; int count = 0; lastDigit = number%10; System.out.println("Last digit: "+lastDigit); int n = number; while(n!=0) { count++; n = n/10; } firstDigit = number/(int)Math.pow(10, count-1); System.out.println("First digit: "+firstDigit); } } |
Output:
First digit: 5
That’s all about how to find first and last digit of number.