★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(shanqingyongzhi)
➤博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/)
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:http://www.javashuo.com/article/p-ojrwbswx-md.html
➤若是連接不是山青詠芝的博客園地址,則多是爬取做者的文章。
➤原文已修改更新!強烈建議點擊原文地址閱讀!支持做者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html
On a broken calculator that has a number showing on its display, we can perform two operations:git
Initially, the calculator is displaying the number X
.github
Return the minimum number of operations needed to display the number Y
.微信
Example 1:spa
Input: X = 2, Y = 3 Output: 2 Explanation: Use double operation and then decrement operation {2 -> 4 -> 3}.
Example 2:code
Input: X = 5, Y = 8 Output: 2 Explanation: Use decrement and then double {5 -> 4 -> 8}.
Example 3:orm
Input: X = 3, Y = 10 Output: 3 Explanation: Use double, decrement and double {3 -> 6 -> 5 -> 10}.
Example 4:htm
Input: X = 1024, Y = 1 Output: 1023 Explanation: Use decrement operations 1023 times.
Note:blog
1 <= X <= 10^9
1 <= Y <= 10^9
在顯示着數字的壞計算器上,咱們能夠執行如下兩種操做:ip
最初,計算器顯示數字 X
。
返回顯示數字 Y
所需的最小操做數。
示例 1:
輸入:X = 2, Y = 3 輸出:2 解釋:先進行雙倍運算,而後再進行遞減運算 {2 -> 4 -> 3}.
示例 2:
輸入:X = 5, Y = 8 輸出:2 解釋:先遞減,再雙倍 {5 -> 4 -> 8}.
示例 3:
輸入:X = 3, Y = 10 輸出:3 解釋:先雙倍,而後遞減,再雙倍 {3 -> 6 -> 5 -> 10}.
示例 4:
輸入:X = 1024, Y = 1 輸出:1023 解釋:執行遞減運算 1023 次
提示:
1 <= X <= 10^9
1 <= Y <= 10^9
Runtime: 8 ms
Memory Usage: 3.9 MB
1 class Solution { 2 func brokenCalc(_ X: Int, _ Y: Int) -> Int { 3 var ret:Int = Int.max 4 for d in 0...30 5 { 6 var t = (X<<d) - Y 7 if t < 0 {continue} 8 var num:Int = d 9 for e in 0..<d 10 { 11 num += t&1 12 t >>= 1; 13 } 14 num += t 15 ret = min(ret, num) 16 } 17 return ret 18 } 19 }
8ms
1 class Solution { 2 func brokenCalc(_ X: Int, _ Y: Int) -> Int { 3 if X >= Y { 4 return X - Y 5 } 6 if Y % 2 == 0 { 7 return 1 + brokenCalc(X, Y / 2) 8 } else { 9 return 1 + brokenCalc(X, Y + 1) 10 } 11 } 12 }