博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
991. Broken Calculator
阅读量:7292 次
发布时间:2019-06-30

本文共 1417 字,大约阅读时间需要 4 分钟。

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 = 3Output: 2Explanation: Use double operation and then decrement operation {2 -> 4 -> 3}.

Example 2:

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

Example 3:

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

Example 4:

Input: X = 1024, Y = 1Output: 1023Explanation: Use decrement operations 1023 times.

Note:

1 <= X <= 10^91 <= Y <= 10^9

难度:medium

题目:在一个显示数字的坏计算器上,我们可以执行两个操作:

加倍:将显示的数字乘以2,或;递减:从显示的数字中减去1。最初,计算器显示的是数字X。返回显示数字Y所需的最小操作数。

思路:从Y到X,可执行的操作为自增1和减半。如果为奇数则自增1,如果为偶则减半。如果X大于Y则只能自减。

Runtime: 3 ms, faster than 100.00% of Java online submissions for Broken Calculator.

Memory Usage: 36.6 MB, less than 100.00% of Java online submissions for Broken Calculator.

class Solution {    public int brokenCalc(int X, int Y) {        int step = 0;        while (X != Y) {            if (Y < X) {                step += X - Y;                break;            }                        Y = Y % 2 == 1 ? Y + 1 : Y / 2;            step++;        }                return step;    }}

转载地址:http://irgjm.baihongyu.com/

你可能感兴趣的文章
第八章 self sizing cell
查看>>
Linux中Nginx中添加自签证书TLS
查看>>
DFS ZOJ 1002/HDOJ 1045 Fire Net
查看>>
BZOJ4946 & 洛谷3826 & UOJ318:[NOI2017]蔬菜——题解
查看>>
10. ZooKeeper之搭建伪集群模式。
查看>>
Easyui Datagrid 如何实现后台交互显示用户数据列表
查看>>
模块登录页代码
查看>>
CCF-CSP 201709-3 JSON查询 题解
查看>>
获取当前路径 ${pageContext.request.contextPath}
查看>>
开博始点,凡程子来了
查看>>
[问题记录]Ubuntu下chmsee安装失败的解决
查看>>
iOS文档注释
查看>>
工厂模式
查看>>
Revit API根据参数类型取得参数的值
查看>>
python18天-pycharm & 正则表达式
查看>>
pdf转txt
查看>>
牛客假日团队赛1 D.Promotion Counting
查看>>
点击头像单独把图片拉取出来.然后再次点击回到初始效果
查看>>
7-2 朋友圈 (25 分)
查看>>
转:手机流畅的决定性因素
查看>>