- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Create palindrome by changing each character to neighboring character in JavaScript
Problem
We are required to write a JavaScript function that takes in a string. Our function can do the following operations on the string −
- each character MUST be changed either to the one before or the one after in the alphabet.
- "a" can only be changed to "b" and "z" to "y".
Our function should return True if at least one of the outcomes of these operations is a palindrome or False otherwise.
Example
Following is the code −
const str = 'adfa'; const canFormPalindrome = (str = '') => { const middle = str.length / 2; for(let i = 0; i < middle; i++){ const first = str[i].charCodeAt() const last = str[str.length - (i + 1)].charCodeAt() const distance = Math.abs(last - first) if(distance > 2 || distance === 1){ return false; }; }; return true; }; console.log(canFormPalindrome(str));
Output
Following is the console output −
true
Advertisements