使用 JavaScript 查找从 m 到 n 所需的最小操作数
问题
我们需要编写一个 JavaScript 函数,该函数将两个数字 m 和 n 作为第一个和第二个参数。
我们的函数应该计算使用以下两个操作从 m 到达 n 所需的最小操作数:
**加倍** - 将显示屏上的数字乘以 2;或
**递减** - 从显示屏上的数字中减去 1。
例如,如果函数的输入为:
const m = 5; const n = 8;
那么输出应该为:
const output = 8;
输出解释
因为操作是:
5 → 4 → 8
Learn JavaScript in-depth with real-world projects through our JavaScript certification course. Enroll and become a certified expert to boost your career.
示例
代码如下:
const m = 5; const n = 8; const findOperations = (m, n) => { let res = 0; while(n > m){ if(n % 2 === 0){ n /= 2; }else{ n += 1; }; res += 1; }; return res + m - n; }; console.log(findOperations(m, n));
输出
控制台输出将为:
2
广告