• js模拟栈---进制转化。十进制转任意进制进制,任意进制转十进制


    	var Stack = (function(){
    		var items = new WeakMap();
    		//先入后出,后入先出
    		class Stack{
    			constructor(){
    				items.set(this,[]);
    			}
    			push(ele){
    				//入栈
    				var ls = items.get(this);
    				ls.push(ele);
    			}
    			pop(){
    				//出栈
    				var ls = items.get(this);
    				return ls.pop();
    			}
    			size(){
    				//获取栈的长度
    				var ls = items.get(this);
    				return ls.length;
    			}
    			print(){
    				//打印栈
    				var ls = items.get(this);
    				return ls.toString();
    			}
    		}
    		return Stack;
    	})();
    
    	/**
    	 * num 需要转化的数字
    	 * base 转化的进制,默认为 2
    	 * */
    	function devide(num,base){
    		base = Math.floor(base) || 2;
    		if(typeof num != "number" || num < 0 || base > 16 || base < 2){
    			throw new Error("参数错误");
    			return '';
    		}
    		num = Math.floor(num);
    
    		var code = "0123456789ABCDEF";
    		var stack = new Stack();
    		var res = '';
    		var rem;
    		while(num > 0){
    			rem = num % base;
    			stack.push(rem);
    			num = Math.floor(num/base);
    		}
    		
    		while(stack.size() > 0){
    			res += code[stack.pop()];
    		}
    		
    		return res;
    	}
      	console.log(devide(15,16))
    

      任意进制转十进制

    		function transfrom(num,base){
    			//任意进制转十进制
    			var bases = [0,1,2,3,4,5,6,7,8,9,"A","B","C","D","E","F"];
    			var config = {};
    			for(var k = 0; k < base; k++){
    				config[bases[k]] = k;
    			}
    			num = String(num);
    			num = num.toUpperCase();
    			var count =  0;
    			var res = 0;
    			var i;
    			while(num.length > 0){
    				i  = num[num.length - 1];
    				i = config[i];
    				res = res + i * Math.pow(base,count);
    				num = num.substr(0,num.length-1);
    				count++;
    			}
    			return res;
    		}
    		
    		console.log(transfrom('ff',16));
    		console.log(transfrom('11',2));
    

      

  • 相关阅读:
    VS1053 datasheet 解读笔记
    C# List Find方法
    git push & git pull 推送/拉取指定分支
    Python 匿名函数
    Python 函数
    java jdk安装与环境变量配置
    Anroid开发环境配置
    Asponse.Cell操作Excel
    C#调试DeBug
    Ext.gridPanel中内容对齐
  • 原文地址:https://www.cnblogs.com/muamaker/p/9181577.html
Copyright © 2020-2023  润新知