zoukankan      html  css  js  c++  java
  • 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;
        }
    }
    
  • 相关阅读:
    PL/SQL会遇到中文插入乱码问题、数据显示不全
    PL/SQL数据生成器
    编程小案例
    MySql案例收集
    关于PL/SQL的安装配置
    Android 歌词桌面同步显示
    DataGridView控件使用大全
    flex java 交互
    Android Launcher 全面剖析
    Android adb 命令
  • 原文地址:https://www.cnblogs.com/mapoos/p/14427645.html
Copyright © 2011-2022 走看看