숫자를 받아 회문 숫자인지 여부를 결정하는 JavaScript 함수를 작성해야 합니다.
회문 수 - 회문 수는 왼쪽과 오른쪽에서 모두 같은 숫자입니다.
예를 들어 -
-
343은 회문 번호입니다.
-
6789876은 회문 번호입니다.
-
456764는 회문 번호가 아닙니다.
예시
이에 대한 코드는 -
const num1 = 343;
const num2 = 6789876;
const num3 = 456764;
const isPalindrome = num => {
let length = Math.floor(Math.log(num) / Math.log(10) +1);
while(length > 0) {
let last = Math.abs(num − Math.floor(num/10)*10);
let first = Math.floor(num / Math.pow(10, length −1));
if(first != last){
return false;
};
num −= Math.pow(10, length−1) * first ;
num = Math.floor(num/10);
length −= 2;
};
return true;
};
console.log(isPalindrome(num1));
console.log(isPalindrome(num2));
console.log(isPalindrome(num3)); 출력
콘솔의 출력은 -
true true false