使用 JavaScript 将数字减到 1
问题
我们要求编写一个 JavaScript 函数,该函数仅接受数字 num 作为唯一参数。
我们的函数只能对 num 执行以下两个操作:如果 num 为偶数,我们可以将 num 替换为 num/2
如果 num 为奇数,我们可以将 num 替换为 num + 1 或 num - 1。
我们的函数仅使用这两个操作的组合,需要计算将 num 变成 1 所需的最少操作数。该函数应返回最少操作数。
例如,如果函数的输入是 -
const num = 7;
则输出应为 -
const output = 4;
输出说明
因为最少可能的运算为 -
7 -> 8 -> 4 -> 2 -> 1 or 7 -> 6 -> 3 -> 2 -> 1
示例
其代码如下 -
const num = 7;
const downToOne = (num = 1) => {
let min = Number.POSITIVE_INFINITY;
let stack = [{ num: num, step: 0 }];
let set = new Set();
let next;
let item;
while (stack.length) {
item = stack.shift();
if (item.num === 1) {
if (min > item.step) {
min = item.step;
}
continue;
}
if (set.has(item.num) || item.step >= min) {
continue;
}
set.add(item.num);
next = item.step + 1;
if (item.num % 2 === 0) {
item.num /= 2;
stack.push({ num: item.num, step: next });
} else {
stack.push({ num: item.num - 1, step: next });
stack.push({ num: item.num + 1, step: next });
}
}
return min;
};
console.log(downToOne(num));输出
控制台中的输出将为 -
4
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP