题目

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:

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

Example 2:

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

Example 3:

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

Example 4:

  1. Input: X = 1024, Y = 1
  2. Output: 1023
  3. 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时,最少操作是X2-1,每次都要考虑是先乘2还是先减1。

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


代码实现

Java

  1. class Solution {
  2. public int brokenCalc(int X, int Y) {
  3. int step = 0;
  4. while (Y > X) {
  5. step++;
  6. if (Y % 2 == 0) {
  7. Y /= 2;
  8. } else {
  9. Y++;
  10. }
  11. }
  12. return step + X - Y;
  13. }
  14. }