Open In App

Check Whether a Year is a Palindrome Year using JavaScript

Last Updated : 14 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

A palindrome year is a year that remains the same when its digits are reversed. For example, 2002 is a palindrome year because it reads the same backward checks whether as forward. In this problem, we’re tasked with checking whether a given year is a palindrome year.

Using string manipulation

In this approach, we convert the year to a string, reverse it, and then compare it with the original string representation of the year.

Example: The below code checks whether a Year is a Palindrome Year using string manipulation in JavaScript.

Javascript
function isPalindromeYear(year) {
    const yearString = year.toString();
    const reversedYearString = yearString
        .split('').reverse().join('');
    return yearString === reversedYearString;
}

console.log(isPalindromeYear(2002));
console.log(isPalindromeYear(2021)); 

Output
true
false


Using Arithmetic Operations

In this approach, we use arithmetic operations to extract the digits of the year one by one, reverse them, and then reconstruct the reversed year. We then compare the reversed year with the original year.

Example: The below code Check Whether a Year is a Palindrome Year using Arithmetic Operations in JavaScript.

Javascript
function isPalindromeYear(year) {
    let reversedYear = 0;
    let originalYear = year;
    while (year > 0) {
        let digit = year % 10;
        reversedYear = reversedYear * 10 + digit;
        year = Math.floor(year / 10);
    }
    return originalYear === reversedYear;
}

console.log(isPalindromeYear(2002));
console.log(isPalindromeYear(2021));

Output
true
false



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads