以 JavaScript 验证数字是否为回文数
假设,我们要编写一个函数,该函数接收一个数字并根据该数字是否为回文数返回布尔值。有一个限制是,我们必须在不将数字转换为字符串或任何其他数据类型的情况下完成此操作。
回文数是指从后往前读与从前往后读都相同的数字。
例如 -
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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP