在 JavaScript 中计算使数字成为回文数所需要的步骤
问题
我们需要编写一个 JavaScript 函数,该函数接受一个数字 num 作为唯一参数。
我们的函数需要返回获得回文数所需要的特殊步骤数。特殊步骤是:“反转数字,将其加到原始数字中”。如果结果数字不是回文数,则重复该过程,直到结果数成为回文数。
例如,如果函数的输入为 -
输入
const num = 87;
输出
const output = 4;
输出说明
因为涉及的步骤为 -
87 + 78 = 165; 165 + 561 = 726; 726 + 627 = 1353; 1353 + 3531 = 4884
示例
如下是代码 -
const num = 87;
const countSteps = (num) => {
let res = 0;
while (!isPalindrome(num)) {
res++
num += +('' + num).split``.reverse().join``
};
return res;
}
const isPalindrome = num => {
let i = 0
let str = '' + num
while (i++ <= str.length / 2) {
if (str[i] !== str[str.length - 1 - i]) return false
};
return true
}
console.log(countSteps(num));输出
4
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP