Python實現:十進位制數與(2~16進位制數)之間的互相轉換
阿新 • • 發佈:2018-12-04
(最開始源於牛客網上的一道程式設計題 : [程式設計題] 數制轉換)
將X進位制轉為int十進位制的功能函式:(乘X次方各位數的加和法)
# 將X進位制轉為int十進位制的功能函式:(乘X次方各位數的加和法) def XToInt(strNum,X): sum = 0 strNum = strNum.lstrip("0") #去掉開始的0(前導零) length = len(strNum) for i in range(length): sum += ABCToNum(strNum[i])*(X**(length-i-1))return sum
將int十進位制轉為Y進位制的功能函式:(除Y取餘法)
# 將int十進位制轉為Y進位制的功能函式:(除Y取餘法) def intToY(num,Y): res = "" while (num!=0): # temp= # temp= res = str(NumToABC(num%Y))+res num = num//Y #取商 # res = int(res) res.upper() return res
其中的輔助函式為:
# 輔助功能函式def ABCToNum(char): if char in "0123456789": return int(char) if char in "Aa" : return 10 if char in "Bb": return 11 if char in "Cc" : return 12 if char in "Dd": return 13 if char in "Ee" : return 14 if char in "Ff":return 15 # 輔助功能函式 def NumToABC(intN): if intN in [0,1,2,3,4,5,6,7,8,9]: return intN if intN ==10 : return 'A' if intN ==11 : return 'B' if intN ==12 : return 'C' if intN ==13 : return 'D' if intN ==14 : return 'E' if intN ==15 : return 'F'
該題的完整實現程式碼:
# 輔助功能函式 def ABCToNum(char): if char in "0123456789": return int(char) if char in "Aa" : return 10 if char in "Bb": return 11 if char in "Cc" : return 12 if char in "Dd": return 13 if char in "Ee" : return 14 if char in "Ff": return 15 # 輔助功能函式 def NumToABC(intN): if intN in [0,1,2,3,4,5,6,7,8,9]: return intN if intN ==10 : return 'A' if intN ==11 : return 'B' if intN ==12 : return 'C' if intN ==13 : return 'D' if intN ==14 : return 'E' if intN ==15 : return 'F' # 將X進位制轉為int十進位制的功能函式:(乘X次方各位數的加和法) def XToInt(strNum,X): sum = 0 strNum = strNum.lstrip("0") #去掉開始的0(前導零) length = len(strNum) for i in range(length): sum += ABCToNum(strNum[i])*(X**(length-i-1)) return sum # 將int十進位制轉為Y進位制的功能函式:(除Y取餘法) def intToY(num,Y): res = "" while (num!=0): # temp= # temp= res = str(NumToABC(num%Y))+res num = num//Y #取商 # res = int(res) res.upper() return res def NumberSystemConversion(): X,strInput,Y = input().split() intA = XToInt(strInput,int(X)) outB = intToY(intA,int(Y)) print(outB) NumberSystemConversion()
結果可以為: