LeetCode:991. Broken Calculator

栏目: 编程工具 · 发布时间: 7年前

内容简介:有一台坏掉的计算器,能够显示一个数字,我们可以对这个数字做两个操作:初始时,计算器显示数字

此文为LeetCode 991. Broken Calculator 的题解。

题意

有一台坏掉的计算器,能够显示一个数字,我们可以对这个数字做两个操作:

  • 乘 二: 将显示的数字乘以2, 或者;
  • 减一 : 将显示的数字减1.

初始时,计算器显示数字 X .

返回要得到数字 Y 需要的最小操作次数。

题解

如果X>Y,则只能执行减一操作。否则,如果Y是奇数,则上一步操作一定是X 减一 ;如果Y是偶数,则上一步操作只能是X 乘二 。

只需要通过上述规则,由Y反推X即可。

代码

/**
 * https://www.robberphex.com/broken-calculator/
 * Runtime: 0 ms, faster than 100.00% of Java online submissions for Broken Calculator.
 * Memory Usage: 33 MB, less than 8.71% of Java online submissions for Broken Calculator.
 */
class Solution {
    public int brokenCalc(int X, int Y) {
        int res = 0;
        // 如果X<Y,则只能-1,故直接走return句
        while (X < Y) {
            if (Y % 2 == 1) {
                Y += 1;
            } else {
                Y /= 2;
            }
            res++;
        }
        return res + X - Y;
    }

    public static void main(String[] args) {
        int res = new Solution().brokenCalc(2, 3);
        System.out.println(res);
    }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。

APIs

APIs

Daniel Jacobson、Greg Brail、Dan Woods / O'Reilly Media / 2011-12-24 / USD 24.99

Many of the highest traffic sites get more than half of their traffic not through the browser but through the APIs they have created. Salesforce.com (more than 50%) and Twitter (more than 75% fall int......一起来看看 《APIs》 这本书的介绍吧!

RGB转16进制工具
RGB转16进制工具

RGB HEX 互转工具

图片转BASE64编码
图片转BASE64编码

在线图片转Base64编码工具

SHA 加密
SHA 加密

SHA 加密工具