Chúng tôi được yêu cầu viết một hàm JavaScript nhận vào một số và xác định xem đó có phải là số palindrome hay không.
Số Palindrome - Số palindrome là số đọc giống nhau từ cả hai phía bên trái và bên phải.
Ví dụ -
-
343 là một số palindrome
-
6789876 là một số palindrome
-
456764 không phải là số palindrome
Ví dụ
Mã cho điều này sẽ là -
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)); Đầu ra
Và đầu ra trong bảng điều khiển sẽ là -
true true false