标签:blog 一个 push lap base turn 过程 数制转换 --
//============================使用Stack类==================================== /** * 1.数制间的相互转换 */ function mulBase(num, base){ var s = new Stack(); do{ s.push(num % base); num = Math.floor(num / base); }while (num > 0); var converted = ""; while(s.length() > 0){ converted += s.pop(); } return converted; } //下面展示了如何使用该方法将数字转换为二进制和八进制数。 var num = 32; var base = 2; var newNum = mulBase(num, base); console.log(num + " converted to base " + base + " is " + newNum); num = 125; base = 8; var newNum = mulBase(num, base); console.log(num + " converted to base " + base + " is " + newNum);
打印如下:
//============================使用Stack类==================================== /** * 2.判断给定字符串是否是回文 */ function isPalindrome(word){ var s = new Stack(); for(var i=0; i<word.length; ++i){ s.push(word[i]); } var rword = ""; while(s.length() > 0){ rword += s.pop(); } if(word == rword){ return true; }else{ return false; } } //测试代码: var word = "hello"; if (isPalindrome(word)) { console.log(word + " is a palindrome."); }else { console.log(word + " is not a palindrome."); } word = "racecar"; if (isPalindrome(word)) { console.log(word + " is a palindrome."); }else { console.log(word + " is not a palindrome."); }
打印:
//============================使用Stack类==================================== /** * 3. 使用栈模拟递归过程 */ function fact(n){ var s = new Stack(); while(n > 1){ s.push(n--); } var product = 1; while(s.length() > 0){ product *= s.pop(); } return product; } console.log(fact(5)); // 显示120
标签:blog 一个 push lap base turn 过程 数制转换 --
原文地址:http://www.cnblogs.com/tenWood/p/7208935.html