예를 들어, 숫자를 받아서 그 숫자가 회문인지 여부에 따라 부울 값을 반환하는 함수를 작성해야 한다고 가정해 보겠습니다. 한 가지 제한 사항은 숫자를 문자열이나 다른 데이터 유형으로 변환하지 않고 이 작업을 수행해야 한다는 것입니다.
회문(Palindrome) 숫자는 앞뒤로 읽어도 같은 숫자입니다.
예를 들어 -
121 343 12321
따라서 이 함수의 코드를 작성해 보겠습니다 -
예시
const isPalindrome = (num) => {
// Finding the appropriate factor to extract the first digit
let factor = 1;
while (num / factor >= 10){
factor *= 10;
}
while (num) {
let first = Math.floor(num / factor);
let last = num % 10;
// If first and last digit not same return false
if (first != last){
return false;
}
// Removing the first and last digit from number
num = Math.floor((num % factor) / 10);
// Reducing factor by a factor of 2 as 2 digits are dropped
factor = factor / 100;
}
return true;
};
console.log(isPalindrome(123241));
console.log(isPalindrome(12321));
console.log(isPalindrome(145232541));
console.log(isPalindrome(1231)); 출력
콘솔의 출력은 다음과 같습니다. -
false true true false