Java Program to Extract Last two Digits of a Given Year
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:
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
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.
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.