使用 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