LeetCode991 broken-calculator

题目

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 <= X <= 10^9
1 <= Y <= 10^9

题解

题目意思就是如何把 X 变成 Y ,但是对于X的操作只能乘2 或者减1然后输出最少的次数。
1.对于 X>Y,我们只要输出 X-Y 就可以了
2.对于 X当Y&1=1时 我们要对其+1,这里就有个问题了为什么是加一而不是减一,因为对于X来说 乘2之后只能减1 也就对应 Y+1 等于 X2。而每次+1都要加一次count(count表示操作次数)每次乘2*也要加一次count,最后得到 count+X-Y

代码

class Solution {
    public int brokenCalc(int X, int Y) {
        int nums = 0;
        if (X > Y) {
            return X - Y;
        }
        while (Y > X) {
            if (Y % 2 == 1) {
                Y++;
                nums++;
            }
            Y >>= 1;
            nums++;
        }
        return nums+X-Y;
    }
}

提交结果

image.png

你可能感兴趣的:(LeetCode991 broken-calculator)