Stack应用 - 十进制转其他进制(2,8,16)

直接贴代码,很简单。通过不断模运算base(进制)。每次取得余数后进栈,最后依次出栈排列。

class Stack:
    def __init__(self):
        self.items = []

    def is_empty(self):
        return self.items == []

    def push(self, item):
        self.items.append(item)

    def pop(self):
        return self.items.pop()

    def peek(self):
        return self.items[-1]

    def size(self):
        return len(self.items)



def base_converter(dec_number, base):
    digits = '0123456789ABCDEF'
    rem_stack = Stack()
    while dec_number > 0:
        rem = dec_number % base
        rem_stack.push(rem)
        dec_number = dec_number // base
    base_string = ''
    while not rem_stack.is_empty():
        base_string = base_string + digits[rem_stack.pop()]
    return base_string
posted @ 2018-10-09 23:02  Jeffrey_Yang  阅读(133)  评论(0编辑  收藏  举报