There is a broken calculator that has the integer startValue on its display initially. In one operation, you can:
multiply the number on display by 2, or
subtract 1 from the number on display.
Given two integers startValue and target, return the minimum number of operations needed to display target on the calculator.
Example 1:
Input: startValue = 2, target = 3
Output: 2
Explanation: Use double operation and then decrement operation {2 -> 4 -> 3}.
Example 2:
Input: startValue = 5, target = 8
Output: 2
Explanation: Use decrement and then double {5 -> 4 -> 8}.
有个计算器,它显示了一个数字startValue, 因为坏掉了,所以只能进行两种运算,
一种是把startValue * 2,另一种是startValue - 1。
问通过多少次运算才能达到target。
思路:
先来看一个简单的情形,startValue > target的时候,
这时显然不能x2,只能往下减,每次只能-1,所以减(startValue - target)次就行了。
startValue < target时,
把startValue往上增就只能x2, 那如果target不是2的倍数怎么办,
不妨反过来考虑,先把target变成2的倍数,
因为startVa

这篇博客讨论了一个损坏计算器的问题,该计算器只能执行乘以2或减去1的操作。文章通过举例说明了如何确定从startValue到达target所需的最小操作数,特别是当startValue大于或小于target时的策略。算法主要涉及数学和递归思想,旨在找到最有效的操作序列。
最低0.47元/天 解锁文章
2068

被折叠的 条评论
为什么被折叠?



