从十进制转换成二进制
function Stack(){
var item = [];
this.push = function(v){
item.push(v);
}
this.pop = function(){
return item.pop();
}
this.peek = function(){
return item[item.length-1];
}
this.isEmpty = function(){
return !item.length;
}
this.clear = function(){
item = [];
}
this.size = function(){
return item.length;
}
this.print = function(){
console.log(item.toString());
}
}
function tenBytwo(Number){
var stack =new Stack(),
remainder,
Binary = '';
while(Number > 0){
remainder = Math.floor(Number % 2);
Number = Math.floor(Number / 2);
stack.push(remainder);
}
while(!stack.isEmpty()){
Binary += stack.pop();
}
console.log(Binary);
}
tenBytwo(133);
逆波兰表示法的计算
function rePoland(arr){
var stack = new Stack();
for(var i=0; i<arr.length; i++){
if(typeof(arr[i]) == 'number'){
stack.push(arr[i]);
}
else if(arr[i] == '+'){
stack.push(stack.pop() + stack.pop());
}
else if(arr[i] == '-'){
var a = stack.peek();
stack.pop();
var b = stack.peek();
stack.push(b - a);
}
else if(arr[i] == '*'){
stack.push(stack.pop() * stack.pop());
}
else{
var a = stack.peek();
stack.pop();
var b = stack.peek();
stack.push(b / a);
}
}
console.log(stack.pop());
}
var arr = [1,2,'+',3,4,'-','*'];
rePoland(arr);
阶乘
function fac(num) {
var factorial = 1,
stack=new Stack();
while(num>0){
stack.push(num--);
}
while(!stack.isEmpty()){
factorial*=stack.pop();
}
console.log(factorial);
}
fac(5);