leetcode 991. Broken Calculator(坏掉的计算器)

There is a broken calculator that has the integer startValue on its display initially. In one operation, you can:

multiply the number on display by 2, or
subtract 1 from the number on display.

Given two integers startValue and target, return the minimum number of operations needed to display target on the calculator.

Example 1:

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

Example 2:

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

有个计算器,它显示了一个数字startValue, 因为坏掉了,所以只能进行两种运算,
一种是把startValue * 2,另一种是startValue - 1。
问通过多少次运算才能达到target。

思路:
先来看一个简单的情形,startValue > target的时候,
这时显然不能x2,只能往下减,每次只能-1,所以减(startValue - target)次就行了。

startValue < target时,
把startValue往上增就只能x2, 那如果target不是2的倍数怎么办,

不妨反过来考虑,先把target变成2的倍数,
因为startValue只能每次-1,反过来就是target只能每次+1。

同样的,startValue只能x2, 那么target就只能除2。
只要能把target移动到startValue就行了。

    public int brokenCalc(int startValue, int target) {
        if(startValue >= target) return startValue - target;
        int result = 0;
        
        while(target > 0) {
            if(startValue >= target) {
                result += (startValue - target);
                return result;
            }
            if(target % 2 == 1) {
                target ++;       
            } else {
                target /= 2;
            }
            result ++;
        }
        return result;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

蓝羽飞鸟

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值