基于JS对象的Stack类及将十进制转化为二进制
class Stack {
constructor () {
this.count = 0
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]
}
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))
将十进制转化为基数为2~36的任意进制
function decimalToBinary (decNumber, base) {
let stack = new Stack()
const digits = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
let rem = 0
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))
console.log(decimalToBinary(11, 2))
console.log(decimalToBinary(233, 2))
console.log(decimalToBinary(1000, 2))
console.log('~~~~~~~~~~~~~~~~~~')
console.log(decimalToBinary(100345, 2))
console.log(decimalToBinary(100345, 8))
console.log(decimalToBinary(100345, 16))
console.log(decimalToBinary(100345, 35))