码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode "483. Smallest Good Base" !!

时间:2017-01-31 10:32:45      阅读:226      评论:0      收藏:0      [点我收藏+]

标签:orm   math   like   ret   min   span   turn   dup   ram   

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

LeetCode "483. Smallest Good Base" !!

标签:orm   math   like   ret   min   span   turn   dup   ram   

原文地址:http://www.cnblogs.com/tonix/p/6358624.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!