Get last digit in a number

Getting last digit in a number
Let me illustrate a very simple logic on getting last digit of a number. The logic is applicable on any programming language and not just in Java. As this is a Java demos blog, I am likely to code it in Java.







import java.util.*;
class GetLastDigit
{
    public static void main(String args[])
    {

    Scanner s=new Scanner(System.in);

    System.out.println("Enter the number");
   
    int n=s.nextInt();
   
    System.out.println("The last digit is "+n%10);
    }
}

There is nothing to explain this code. n%10  returns the remainder when the number is divided by 10. That's it. It is obvious that the multiples of 10 end with 0. So the remainder is the last digit. When you want to get all the digits excluding the last digit, simply replace % with / in the above program.Simple is that.


Posted by at on

Tags: Playing with Numbers,