Tony's Log

Algorithms, Distributed System, Machine Learning

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::
  502 随笔 :: 0 文章 :: 3 评论 :: 11万 阅读
< 2025年1月 >
29 30 31 1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31 1
2 3 4 5 6 7 8

A more programming-like solution, is to hack the problem from simple: we try each possble base value, and see which 111..11 fits target number - using binary search.

复制代码
class Solution(object):
    def helper(self, num, p):
        l = 1; r = int(pow(num, 1.0/p) + 1) # find highest possible bit
        while(l < r):
            mid = l + (r - l) // 2
            sum = 0; cur = 1
            # Addup to sum by form of 1111..11
            for i in xrange(0, p + 1):
                sum += cur
                cur *= mid
            # Good?
            if sum == num:
                return mid
            elif sum > num:
                r = mid
            else:
                l = mid + 1
                
        return -1
        
    def smallestGoodBase(self, N):
        n = int(N)
        
        # iterate each base, from longest 1s to shortest
        for p in xrange(2, 101):
            if (1 << p) < n:
                k = self.helper(n, p)
                if k != -1:
                    return str(int(k))
        
        return str(n-1) # 11
        
复制代码

However, as you expect, there's a smarter, math solution.

https://discuss.leetcode.com/topic/76368/python-solution-with-detailed-mathematical-explanation-and-derivation

posted on   Tonix  阅读(264)  评论(0编辑  收藏  举报
努力加载评论中...
点击右上角即可分享
微信分享提示