LeetCode 991. 坏了的计算器

题目描述

991. 坏了的计算器

思路分析

解法一:逆向贪心(推荐)

核心思路

  • target 反向操作到 startValue
  • target 为奇数,只能 +1;为偶数则 /2 更优。
  • 最后补上差值即可。


复杂度分析

  • 时间复杂度:O(log target)。
  • 空间复杂度:O(1)。
class Solution {
    public int brokenCalc(int startValue, int target) {
        int ops = 0;
        while (target > startValue) {
            if ((target & 1) == 1) {
                target++;
            } else {
                target >>= 1;
            }
            ops++;
        }
        return ops + (startValue - target);
    }
}
func brokenCalc(startValue int, target int) int {
	ops := 0
	for target > startValue {
		if target%2 == 1 {
			target++
		} else {
			target /= 2
		}
		ops++
	}
	return ops + (startValue - target)
}

相似题目

题目 难度 考察点
69. x 的平方根 简单 二分
754. 到达终点数字 中等 数学
65. 有效数字 困难 字符串解析
670. 最大交换 中等 贪心
171. Excel 表列序号 简单 数学
本文作者:
本文链接: https://hgnulb.github.io/blog/2022/77741792
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议,转载请注明出处!