[LeetCode] 991. Broken Calculator

On a broken calculator that has a number showing on its display, we can perform two operations:

  • Double: Multiply the number on the display by 2, or;
  • Decrement: Subtract 1 from the number on the display.

Initially, the calculator is displaying the number X.

Return the minimum number of operations needed to display the number Y.

Example 1:

Input: X = 2, Y = 3
Output: 2
Explanation: Use double operation and then decrement operation {2 -> 4 -> 3}.

Example 2:

Input: X = 5, Y = 8
Output: 2
Explanation: Use decrement and then double {5 -> 4 -> 8}.

Example 3:

Input: X = 3, Y = 10
Output: 3
Explanation:  Use double, decrement and double {3 -> 6 -> 5 -> 10}.

Example 4:

Input: X = 1024, Y = 1
Output: 1023
Explanation: Use decrement operations 1023 times.

Note:

  1. 1 <= X <= 10^9
  2. 1 <= Y <= 10^9

坏了的计算器。

在显示着数字的坏计算器上,我们可以执行以下两种操作:

双倍(Double):将显示屏上的数字乘 2;
递减(Decrement):将显示屏上的数字减 1 。
最初,计算器显示数字 X。

返回显示数字 Y 所需的最小操作数。 

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/broken-calculator
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

这道题的思路是递归 + 贪心。题意是需要将X转换成Y,规则是只能将X乘以2,或者将X减一。这里我们可以把思路转换一下,X * 2其实是Y / 2,X - 1 其实是Y + 1。这个思路的来源是如果你正向思考这个问题,一直将X * 2,其实是很难找到一个停止点的,因为你不知道X * 2的操作要做多少次才行。所以在逆向思考这个问题的时候,如果Y是偶数,那么我们递归去看X变化成Y / 2的操作步数;如果Y是奇数,那么我们递归去看X变化成Y + 1的操作步数(Y + 1是个偶数)。

时间O(logY)

空间O(1)

Java实现

1 class Solution {
2     public int brokenCalc(int X, int Y) {
3         if (X >= Y) {
4             return X - Y;
5         }
6         return (Y & 1) == 0 ? 1 + brokenCalc(X, Y / 2) : 1 + brokenCalc(X, Y + 1);
7     }
8 }

LeetCode 题目总结

原文地址:https://www.cnblogs.com/cnoodle/p/14434939.html