结合stack数据结构,实现不同进制转换的算法

时间:2022-11-05 22:26:22
#!/usr/bin/env python
# -*- coding: utf-8 -*-

# learn <<Problem Solving with Algorithms and Data Structures>>
# Release 3.0
# chengang882 @ 2016-12-20
# 它可以将十进制转换成二进制,八进制和十六进制
# Completed implementation of a stack ADT

#数据结构
class Stack(object):
    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[len(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

    new_string = ""
    if base == 8:
        new_string = "0"
    if base == 16:
        new_string = "0x"
    while not rem_stack.is_empty():
        new_string += digits[rem_stack.pop()]

    return new_string

if __name__ == "__main__":
    print(base_converter(42, 2))
    print(base_converter(25, 16))
    print(base_converter(424, 8))
    print(base_converter(4132, 16))

  输出 :

>>>
101010
0x19
0650
0x1024
>>>