3-7 思考题

来源:3-5 LeetCode:144. 二叉树的前序遍历

烈霓殇

2021-04-17

1、Stack 类

class Stack {
  constructor(list = []) {
    this.stack = list;
  }
  pop() {
    return this.stack.splice(this.stack.length - 1, 1)[0];
  }
  push() {
    const args = [].slice.call(arguments);
    this.stack = [...this.stack, ...args];
    return this.stack.length;
  }
  peek() {
    return this.stack[this.stack.length - 1];
  }
  empty() {
    return this.stack.length === 0;
  }
}

2、将 100 转换为 二进制

function convertToB(value) {
  if(value <= 1) {
    return value;
  }
  let stack = [];
  let binary = '';
  while (value > 0) {
    rem = value % 2;
    value = Math.floor(value / 2);
    stack.push(rem);
  }
  while (stack.length) {
    binary = `${binary}${stack.pop()}`;
  }
  return binary;
}
写回答

1回答

lewis

2021-04-17

good

0
0

JavaScript版数据结构与算法 轻松解决前端算法面试

夯实算法基础,填补技术短板,助力面试考题最后一公里

2421 学习 · 670 问题

查看课程