0991. Broken Calculator (M)

Broken Calculator (M)

题目

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

题意

给定整数X和Y,可以对X进行两种操作:乘2和减1,问经过最少多少次操作能把X变为Y。

思路

正向推的话不容易,比如X=3,Y=4时,最少操作是(X-1)*2,而X=3,Y=5时,最少操作是X*2-1,每次都要考虑是先乘2还是先减1。

反向推导,Y有两种操作:除以2和加1。有以下几种情况:当Y<X时,只能加1;当Y>X时,如果Y是奇数,则只能加1,如果Y是偶数,有两种操作:除以2,或者加2后再除以2,很明显后一种操作的结果与除以2后再加1等价,但多了一步操作,所以当Y是偶数时只需要除以2。


代码实现

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;
    }
}
posted @ 2021-02-21 22:40  墨云黑  阅读(42)  评论(0编辑  收藏  举报