题目
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 = 3Output: 2Explanation: Use double operation and then decrement operation {2 -> 4 -> 3}.
Example 2:
Input: X = 5, Y = 8Output: 2Explanation: Use decrement and then double {5 -> 4 -> 8}.
Example 3:
Input: X = 3, Y = 10Output: 3Explanation: Use double, decrement and double {3 -> 6 -> 5 -> 10}.
Example 4:
Input: X = 1024, Y = 1Output: 1023Explanation: Use decrement operations 1023 times.
Note:
1 <= X <= 10^91 <= Y <= 10^9
题意
给定整数X和Y,可以对X进行两种操作:乘2和减1,问经过最少多少次操作能把X变为Y。
思路
正向推的话不容易,比如X=3,Y=4时,最少操作是(X-1)2,而X=3,Y=5时,最少操作是X2-1,每次都要考虑是先乘2还是先减1。
反向推导,Y有两种操作:除以2和加1。有以下几种情况:当Y
代码实现
Java
class Solution {public int brokenCalc(int X, int Y) {int step = 0;while (Y > X) {step++;if (Y % 2 == 0) {Y /= 2;} else {Y++;}}return step + X - Y;}}
