Print age (with.Java)
This is an article looking into the “age output” problem.
As I solve coding test problems, I look back on the problems I solved and look into different solution methods to learn more.
Let’s look at the problem first.
problem
I wondered what year the shy 40-year-old teacher was born.
When age is given, please complete the solution function that returns the year of birth based on 2022.
Restrictions
0 < age ≤ 120
Age is 1 year in the year of birth and increases by 1 for each year.
Input/Output Example
age | result |
---|---|
40 | 1983 |
23 | 2000 |
My solution to the problem
class Solution {
public int solution(int age) {
int answer = 0;
answer = 2022 - age + 1;
return answer;
}
}
Solution explanation
Based on 2022, we wrote the code answer = 2022 - age + 1;: to reflect the fact that the age is subtracted from the value starting from 1 year old to satisfy the restrictions.