reverse string
// --- Directions
// Given a string, return a new string with the reversed
// order of characters
// --- Examples
// reverse('apple') === 'leppa'
// reverse('hello') === 'olleh'
// reverse('Greetings!') === '!sgniteerG'
function reverse1(str) {
const arr = str.split('');
arr.reverse();
return arr.join();
// Save as => str.split('').reverse().join();
}
function reverse2(str) {
let reversed = '';
for (const character of str) {
reversed = character + reversed;
}
return reversed;
}
function reverse3(str) {
str.split('').reduce((reversed, character) => {
return character + reversed;
}, '');
return reversed;
}
palindrome
// --- Directions
// Given a string, return true if the string is a palindrome
// or false if it is not. Palindromes are strings that
// form the same word if it is reversed. *Do* include spaces
// and punctuation in determining if the string is a palindrome.
// --- Examples:
// palindrome("abba") === true
// palindrome("abcdefg") === false
// 위 reverse string 문제를 활용한 방법.
function palindrome1(str) {
const reversed = str.split('').reverse().join('');
return str === reversed;
}
// every 메소드를 활용해 한글자씩 비교하여 해결하는 방법.
function palindrome2(str) {
return str.split('').every((char, i) => {
return char === str[str.length - i - 1];
})
}
reverse int
// --- Directions
// Given an integer, return an integer that is the reverse
// ordering of numbers.
// --- Examples
// reverseInt(15) === 51
// reverseInt(981) === 189
// reverseInt(500) === 5
// reverseInt(-15) === -51
// reverseInt(-90) === -9
function reverseInt1(n) {
const reversed = n.toString().split('').reverse().join('');
return parseInt(reversed) * Math.sign(n);
}
module.exports = reverseInt;