Stack structure is a common data structure, for example, we used it will be a decimal number into a binary number revolutions method - modulo 2 addition method.
Our 100 as an example, operation is as follows:
The results are written from bottom to top as follows:
Obviously we need
1. Every time the remainder by 2 onto the stack.
2. divided by 2 as a result of the next operand.
3. Repeat the above steps until the two operands is 0.
4. 0 and pop from the stack 1, to give a final binary sequence is also desired.
Algorithm implementation process is not particularly complicated, like this:
Here is a running instance:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <Title> stack structure </ title> </head> <body> <script> function Stack(){ this.items=[]; //进栈操作 Stack.prototype.push=function(element){ this.items.push(element); } // pop operations Stack.prototype.pop = function () { return the this .items.pop (); } // See top element Stack.prototype.peek = function () { return the this .items [ the this .items.length-. 1 ]; } // Check whether the stack is empty Stack.prototype.isEmpty = function () { return the this .items.length == 0 ; } //打印栈 Stack.prototype.toString=function(){ var resultString=''; for(var i=0;i<this.items.length;i++){ resultString+=this.items[i]+' '; } return resultString; } } // function: to convert decimal to binary function DEC2BIN (decNumber) { // 1. stack objects defined var Stack = new new Stack (); // 2. cycling the while (decNumber> 0 ) { // 2.1 to get the remainder, and placed in the stack stack.push (decNumber% 2 ); // a result of calculation for obtaining the divisible 2.2 decNumber=Math.floor(decNumber/2); } // returns 0 and 1 from the stack var binaryString = '' ; the while (! Stack.isEmpty ()) { binaryString+=stack.pop(); } return binaryString; } // test function binary decimal turn Alert (DEC2BIN (100 )); </ Script> </body> </html>
Results are as follows: