As the name suggests where there is an execution to be operated required to deal with digits of the number, the modulo operator plays a vital role. Here the goal is to extract the last digits of a number. So making the problem easier to think about what if the goal is to extract the last digit from a number. Here in this case number is representing the year. The mathematical concept involved in extracting the last is to divide the given number by such a number that the remainder should be the same as that of the last digit. In order to extract the last digit that number with which the given number has to be divided must be 10.
Modulo is represented by ‘%’ and is used to get the remainder
Example: Extracting Last One Digit From A Number
Random Number = 1997 Last Digit = 7 Goal: 1997 % (x) = 7 // Goal is Divide 1997 by x such that remainder is 7 if x = 10 // 1997 % 10 = 7 that is the last digit
Now, in order to extract the last two digits, we will be treating the number with the same approach just the given number will be modulo by 100 as per the mathematics unit standard.
Example: Extracting the Last Two-Digit From A Number
Input : year = 2020 Output : 20 Input : year = 1983 Output : 83 Input : year = 2000 Output : 00
We can implement this using 2 different methods:
- Using Modulo Arithmetic Operator
- Using String substring() method
A. Using Modulo Arithmetic Operator: We can use the modulo operator (%) to extract the last two digits by taking the modulo of the year by 100.
Internal Working Of Mathematics Unit System
Let us consider 1983, we can write it as 1983 = 1*1000 + 9*100 + 8*10 + 3 So when we take modulo by 100, we will just have the last two digits as remainder. 1983 % 100 = 1*1000 % 100 + 9*100 % 100 + 8*10 % 100 + 3 % 100 = 0 + 0 + 8*10 + 3 = 83
The implementation of the above approach is described below
// Java code to extract last two digits of a year // Importing Classes/Files import java.util.*;
public class GFG {
// Main Driver Code
public static void main(String args[])
{
// Initializing year as String
int year = 1983 ;
// Printing last two digits of a number
// by modulo with 100
System.out.print(year % 100 );
}
} |
83
B. Using String substring() method: This method returns a new string that is a substring of the given string. Thus, to extract the last two digits we need to get the substring after index 2.
// Java code to extract last two digits of a year public class GFG {
// Function to extract last to digits of a year
static int extractLastTwo(String year)
{
// using substring() to extract the last two digit
// as substring
String lastTwoDigits = year.substring( 2 );
return Integer.parseInt(
lastTwoDigits); // Returning last two digits as
// an integer
}
public static void main(String args[])
{
// Initializing year as String
String year = "1983" ;
System.out.print(extractLastTwo(year));
}
} |
83