shadow's Blog

Happy coding

数的表示

shadow posted @ 2014年5月29日 10:25 in python , 836 阅读

将一个整数转换为3的指数加减的形式,如7转换为30-31+32

# -*- coding: utf-8 -*-
def inttoint3(num):
    ret=[]
    tmp=num
    while tmp!=0:
        ret.append(tmp%3)
        tmp/=3
    ret.append(tmp)
    return ret

def int3tostring3(num):
    pnum=0#负数标志
    if num<0:
        num=-num
        pnum=1
    lst=inttoint3(num)#十进制转换为三进制
    ll=len(lst)
    res=[0]*ll
    flag=0#进位标志
    for i in range(ll):
        lst[i]+=flag
        if lst[i]==1 or lst[i]==0:
            res[i]=lst[i]
            flag=0
        elif lst[i]==2:
            res[i]=-1
            flag=1
        elif lst[i]==3:
            res[i]==0
            flag=1
    if i>0 and res[i]==0:
        res.pop()
        ll-=1
#print res,ll
    if pnum==1:
        for j in range(ll):
            res[j]=0-res[j]
    return res
if __name__=="__main__":
    num=[-3,-7,0,1,2,3,4,7,11,28]
    for i in num:
        print int3tostring3(i)

Avatar_small
AP 10th Maths Questi 说:
2022年9月11日 17:02

Mathematics is one of the tough subjects and also an easy subject for class 10th standard students of TM, EM, AP 10th Maths Question Paper UM and HM studying at government and private schools of the state. Department of School Education and teaching staff of various institutions have designed and suggested the Mathematics question paper with solutions for all chapters topic wide for each lesson of the course, and the AP SSC Maths Model Paper 2023 Pdf designed based on the new revised syllabus and curriculum.

Avatar_small
seo service UK 说:
2024年2月21日 15:22

I wanted to thank you for this great read!! I definitely enjoying every little bit of it I have you bookmarked to check out new stuff you post


登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter