在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★ On a broken calculator that has a number showing on its display, we can perform two operations:
Initially, the calculator is displaying the number Return the minimum number of operations needed to display the number Example 1: Input: X = 3
Output: 2
Explanation: Use double operation and then decrement operation {2 -> 4 -> 3}.
Example 2: Input: X = 8
Output: 2
Explanation: Use decrement and then double {5 -> 4 -> 8}.
Example 3: Input: X = 10
Output: 3
Explanation: Use double, decrement and double {3 -> 6 -> 5 -> 10}.
Example 4: Input: X = 1
Output: 1023
Explanation: Use decrement operations 1023 times.
Note:
在显示着数字的坏计算器上,我们可以执行以下两种操作:
最初,计算器显示数字 返回显示数字 示例 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 次 提示:
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 }
|
请发表评论