Python實現十進位制向2,8,16等進位制轉換演算法
阿新 • • 發佈:2019-01-09
from pythonds.basic.stack import Stack def divideBy2(decNumber, base): digits = "0123456789ABCDEF" remstack = Stack() while decNumber > 0: rem = decNumber % base remstack.push(rem) decNumber = decNumber // base binString = "" while not remstack.isEmpty(): if base > 10: top = str(digits[remstack.pop()]) binString = binString + top else: binString = binString + str(remstack.pop()) return binString if __name__ == '__main__': print(divideBy2(26, 16)) print(divideBy2(26, 9)) print(divideBy2(26, 5)) print(divideBy2(26, 8))