js 栈应用 进制互转

定义栈

	function Stack() {
			// var items = []
			window.items = [] // 方便浏览器调试
			this.push = function (e) {
				items.push(e)
			}

			this.pop = function (e) {
				return items.pop()
			}

			this.peek = function (e) {
				return items[(items.length - 1)]
			}

			this.isEmpty = function (e) {
				return items.length == 0
			}

			this.size = function (e) {
				return items.length
			}

			this.clear = function (e) {
				items = []
			}

			this.print = function (e) {
				console.log(items.toString())
			}
		}

定义转换方法

function baseConverter(decNumber, base) {
			// debugger;
			let remStack = new Stack(),
				rem,
				baseString = '',
				digits = '0123456789ABCDEF'

			while (decNumber > 0) {
				rem = Math.floor(decNumber % base)
				remStack.push(rem)
				decNumber = Math.floor(decNumber / base)
			}

			while (!remStack.isEmpty()) {
				console.log(items)
				let idx = remStack.pop()
				console.log(idx)
				baseString += digits[idx]
			}

			return baseString
		}
baseConverter(100345, 8) // 303771
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值