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);