栈及栈的应用

119 阅读1分钟

基于JS对象的Stack类及将十进制转化为二进制

class Stack { // pop、push、peek事件复杂度为:O(1)
  constructor () {
    this.count = 0 // 相当于length,记录栈的长度及帮助我们从栈中添加和删除元素
    this.items = {}
  }

  // 添加一个(或几个)新元素到栈顶
  push (element) {
    this.items[this.count] = element
    this.count++
  }
  // 移除栈顶元素,同时返回被移除的元素
  pop () {
    if (this.isEmpty()) {
      return undefined
    }
    this.count--
    const result = this.items[this.count]
    delete this.items[this.count]

    return result
  }
  // 返回栈顶的元素,不对栈进行任何修改
  peek () {
    if (this.isEmpty()) {
      return undefined
    }
    return this.items[this.count-1]
  }
  // 判断栈是否为空,为空返回true,否则返回false
  isEmpty () {
    return this.count === 0
  }
  // 返回栈中元素的个数
  size () {
    return this.count
  }
  // 移除栈中的所有元素
  clear () {
    this.count = 0
    this.items = {}
  }

  // 打印栈的内容
  toString () {
    if (this.isEmpty()) return ''
    let objString = `${this.items[0]}`
    for (let i=0; i<this.count-1; i++) {
      objString += (', ' + this.items[i+1])
    }
    return objString
  }
}

// 将十进制输出为二进制
function decimalToBinary (decNumber) {
  let stack = new Stack()
  let temp = 0
  while (decNumber/2) {
    temp = decNumber%2
    stack.push(temp)
    decNumber = Math.floor(decNumber / 2)
  }

  let str = ''
  for (let i=0; i<stack.size(); i++) {
    str += stack.pop()
    i--
  }
  return str
}
console.log(decimalToBinary(10)) // 1010

将十进制转化为基数为2~36的任意进制

function decimalToBinary (decNumber, base) {
  let stack = new Stack()
  const digits = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
  let rem = 0
  // if (!(base>=2 && base<=36)) return ''
  if (base<2 || base>36) return ''

  while (decNumber/base) {
    rem = decNumber%base
    stack.push(rem)
    decNumber = Math.floor(decNumber / base)
  }

  let str = ''
  for (let i=0; i<stack.size(); i++) {
    str += digits[stack.pop()]
    i--
  }
  return str
}
console.log(decimalToBinary(10, 2)) // 1010
console.log(decimalToBinary(11, 2)) // 1011
console.log(decimalToBinary(233, 2)) // 11101001
console.log(decimalToBinary(1000, 2)) // 1111101000

console.log('~~~~~~~~~~~~~~~~~~')
console.log(decimalToBinary(100345, 2)) // 11000011111111001
console.log(decimalToBinary(100345, 8)) // 303771
console.log(decimalToBinary(100345, 16)) // 187F9
console.log(decimalToBinary(100345, 35)) // 2BW0