作者: 负雪明烛
id: fuxuemingzhu
个人博客: http://fuxuemingzhu.cn/


题目地址:https://leetcode.com/problems/broken-calculator/

题目描述

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

题目大意

有一个坏掉了的计算器,只能对现在正在显示的数字进行两种操作:

  1. 翻倍
  2. 减1

已知初始化的时候计算器显示的数字是X,问最少需要多少步操作才能得到目标数字Y。

解题方法

这个题第一感觉肯定是BFS,但是很显然数字的取值范围太大,BFS会超时。

那么这个题就是个数学问题了……下面的内容摘自演员的自我修养

  1. 首先我们发现x要么乘2要么减1,如果x初始就比y大,那么只能一直做减法!

  2. 在x小于y的情况下:

  • 如果y是奇数,那么最后一个操作一定是减1(显然)
  • 如果y是偶数呢?最后操作一定是乘2吗?答案是yes!

因为对于某个x现在要变为y可能是先乘2再做若干次减法,也可能是先做若干次减法再乘2
第一种用式子表示为1 + 2*x-y,第二种用式子表示为x-y/2 + 1
显然式子2的结果永远小于等于式子1的结果!

所以,我们想要最小化次数一定是先减法再乘2,也就是y为偶数时,最后的操作一定是乘2。

那么这里我们就从y开始反推,是奇数就加1,是偶数就除2,一直到y小于等于x为止!

python代码如下:

class Solution(object):
def brokenCalc(self, X, Y):
"""
:type X: int
:type Y: int
:rtype: int
"""
if X > Y: return X - Y
res = 0
while X < Y:
if Y % 2 == 1:
Y += 1
res += 1
Y //= 2
res += 1
return res + X - Y

日期

2019 年 2 月 21 日 —— 一放假就再难抓紧了

最新文章

  1. jQuery下拉框扩展和美化插件Chosen
  2. CI在ngnix的配置
  3. 【Alpha版本】冲刺阶段——Day 9
  4. MySQL 5.7 深度解析: 半同步复制技术
  5. Win7 64位 Visio反向工程(MySQL)
  6. Linux命令(14)文件和文件夹权限管理:chmod
  7. ruby关于flip-flop理解上一个注意点
  8. 关于C#中文本模板(.tt)的简单应用
  9. Codeforces Round #140 (Div. 1) D. The table 构造
  10. mongodb工具
  11. iOS AVAudioPlayer 提示音
  12. 射频识别技术漫谈(26)——Felica的文件系统
  13. BZOJ 1615: [Usaco2008 Mar]The Loathesome Hay Baler麻烦的干草打包机
  14. javaWeb基础核心之一Servlet
  15. Windows 部署 Redis 群集(转)
  16. 【Python3爬虫】用Python发送天气预报邮件
  17. 【动态规划】最大连续子序列和,最大子矩阵和,最大m子段和
  18. CentOS6.5安装Scrapy
  19. 【转】Linux配置NTP时间同步服务器
  20. jsp el的内置对象

热门文章

  1. EPOLL原理详解(图文并茂)
  2. MybatisPlus使用Wrapper实现查询功能
  3. 学习java的第十三天
  4. day05 连表查询与子查询
  5. VSCode+Maven+Hadoop开发环境搭建
  6. 安全相关,CSRF
  7. java标识接口
  8. 【Service】【Database】【Oracle】Oracle client 12.1.0.2 for MacOS
  9. springmvc框架找那个@responseBody注解
  10. 用户信息系统_serviceImpl