js栈的封装,十进制转任意进制


js栈的封装,十进制转任意进制

class Stack {
           constructor() {
               this.items = []
           }
           push(data) {
               this.items.push(data)
           }
           pop() {
               return this.items.pop()
           }
           peek() {
               return this.items[this.items.length - 1]
           }
           isEmpty() {
               return this.items.length === 0
           }
           size() {
               return this.items.length
           }
           clear() {
               this.items = []
           }
           toString() {
               return this.items.join()
           }
       }
       function convert(data, base) {
           let stack = new Stack()
           let string = ""
           let number = data
           let baseString = "0123456789ABCDEF"
           while (number > 0) {
               stack.push(number % base)
               number = Math.floor(number / base)
           }
           while (!stack.isEmpty()) {
               string += baseString[stack.pop()]
           }
           return string
       }
       let res = convert(500, 16)
       console.log(res);

文章作者: TOBY
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 TOBY !
评论
  目录