[Swift]LeetCode483. 最小好进制 | Smallest Good Base
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
?微信公眾號:山青詠芝(shanqingyongzhi)
?博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/)
?GitHub地址:https://github.com/strengthen/LeetCode
?原文地址:https://www.cnblogs.com/strengthen/p/10348502.html?
?如果鏈接不是山青詠芝的博客園地址,則可能是爬取作者的文章。
?原文已修改更新!強烈建議點擊原文地址閱讀!支持作者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
For an integer n, we call k>=2 a?good base?of n, if all digits of n base k are 1.
Now given a string representing n, you should return the smallest good base of n in string format.?
Example 1:
Input: "13" Output: "3" Explanation: 13 base 3 is 111.?Example 2:
Input: "4681" Output: "8" Explanation: 4681 base 8 is 11111.?Example 3:
Input: "1000000000000000000" Output: "999999999999999999" Explanation: 1000000000000000000 base 999999999999999999 is 11.?Note:
對于給定的整數 n, 如果n的k(k>=2)進制數的所有數位全為1,則稱?k(k>=2)是 n 的一個好進制。
以字符串的形式給出 n, 以字符串的形式返回 n 的最小好進制。?
示例 1:
輸入:"13" 輸出:"3" 解釋:13 的 3 進制是 111。示例 2:
輸入:"4681" 輸出:"8" 解釋:4681 的 8 進制是 11111。示例 3:
輸入:"1000000000000000000" 輸出:"999999999999999999" 解釋:1000000000000000000 的 999999999999999999 進制是 11。?提示:
12ms
1 class Solution { 2 func smallestGoodBase(_ n: String) -> String { 3 var num:Int = Int(n)! 4 for i in (2...(Int(log(Double(num + 1)) / log(2)))).reversed() 5 { 6 var left:Int = 2 7 var right:Int = Int(pow(Double(num), 1.0 / Double(i - 1))) + 1 8 while (left < right) 9 { 10 var mid:Int = left + (right - left) / 2 11 var sum:Int = 0 12 for j in 0..<i 13 { 14 sum = sum * mid + 1 15 } 16 if sum == num {return String(mid)} 17 else if sum < num {left = mid + 1} 18 else {right = mid} 19 } 20 } 21 return String(num - 1) 22 } 23 }?
轉載于:https://www.cnblogs.com/strengthen/p/10348502.html
總結
以上是生活随笔為你收集整理的[Swift]LeetCode483. 最小好进制 | Smallest Good Base的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: C++Primer第五版学习笔记
- 下一篇: SSH框架介绍