How to convert an integer to a string in any base?

前端 未结 27 3146
清歌不尽
清歌不尽 2020-11-22 02:25

Python allows easy creation of an integer from a string of a given base via

int(str, base). 

I want to perform the inverse: creati

27条回答
  •  花落未央
    2020-11-22 02:47

    def int2base(a, base, numerals="0123456789abcdefghijklmnopqrstuvwxyz"):
        baseit = lambda a=a, b=base: (not a) and numerals[0]  or baseit(a-a%b,b*base)+numerals[a%b%(base-1) or (a%b) and (base-1)]
        return baseit()
    

    explanation

    In any base every number is equal to a1+a2*base**2+a3*base**3... The "mission" is to find all a 's.

    For everyN=1,2,3... the code is isolating the aN*base**N by "mouduling" by b for b=base**(N+1) which slice all a 's bigger than N, and slicing all the a 's that their serial is smaller than N by decreasing a everytime the func is called by the current aN*base**N .

    Base%(base-1)==1 therefor base**p%(base-1)==1 and therefor q*base^p%(base-1)==q with only one exception when q=base-1 which returns 0. To fix that in case it returns 0 the func is checking is it 0 from the beggining.


    advantages

    in this sample theres only one multiplications (instead of division) and some moudulueses which relatively takes small amounts of time.

提交回复
热议问题