1. 程式人生 > >Python實現十進位制向2,8,16等進位制轉換演算法

Python實現十進位制向2,8,16等進位制轉換演算法

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))