[Swift]LeetCode483. 最小好進制 | Smallest Good Base

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(shanqingyongzhi)
➤博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:http://www.javashuo.com/article/p-xyrenobb-me.html 
➤若是連接不是山青詠芝的博客園地址,則多是爬取做者的文章。
➤原文已修改更新!強烈建議點擊原文地址閱讀!支持做者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html

For an integer n, we call k>=2 a good base of n, if all digits of n base k are 1.git

Now given a string representing n, you should return the smallest good base of n in string format. github

Example 1:微信

Input: "13"
Output: "3"
Explanation: 13 base 3 is 111. 

Example 2:spa

Input: "4681"
Output: "8"
Explanation: 4681 base 8 is 11111. 

Example 3:code

Input: "1000000000000000000"
Output: "999999999999999999"
Explanation: 1000000000000000000 base 999999999999999999 is 11. 

Note:orm

  1. The range of n is [3, 10^18].
  2. The string representing n is always valid and will not have leading zeros.

對於給定的整數 n, 若是n的k(k>=2)進制數的全部數位全爲1,則稱 k(k>=2)是 n 的一個好進制htm

以字符串的形式給出 n, 以字符串的形式返回 n 的最小好進制。 blog

示例 1:字符串

輸入:"13"
輸出:"3"
解釋:13 的 3 進制是 111。

示例 2:

輸入:"4681"
輸出:"8"
解釋:4681 的 8 進制是 11111。

示例 3:

輸入:"1000000000000000000"
輸出:"999999999999999999"
解釋:1000000000000000000 的 999999999999999999 進制是 11。 

提示:

  1. n的取值範圍是 [3, 10^18]。
  2. 輸入老是有效且沒有前導 0。

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 }
相關文章
相關標籤/搜索