Find the kth eleven-non-free number

前端 未结 8 2123
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-02-04 10:10

Let\'s define eleven-non-free numbers:

If we consider a number as a string, then if any substring inside is a (non-zero) power of 11, then this

8条回答
  •  孤城傲影
    2021-02-04 10:36

    This looks like an O(klog^2(k)) algorithm:

    def add(vals, new_vals, m, val):
        if val < m and val not in vals and val not in new_vals:
            new_vals.append(val)
    
    def kth11(k):
        vals = [ 11**i for i in range(1, k+1) ]
        new_vals = [ ]
        while True:
            vals = sorted(vals + new_vals)
            vals = vals[:k]
            m = vals[-1]
            new_vals = [ ] 
            for v in vals:
                for s in range(1, 10):
                    val = int(str(s) + str(v))
                    add(vals, new_vals, m, val)
                for s in range(0, 10):
                    val = int(str(v) + str(s))
                    add(vals, new_vals, m, val)
            if len(new_vals) == 0: break
        return vals[-1]
    
    print kth11(130)
    

提交回复
热议问题