A Pen by Gabriel do Nascimento Barbier on CodePen.
Last active
July 12, 2016 03:14
-
-
Save barbier/d052d81381c45768d653d0670d3a3715 to your computer and use it in GitHub Desktop.
Base converter
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function Stack() { | |
var items = []; | |
this.push = function(element) { | |
items.push(element); | |
} | |
this.pop = function() { | |
return items.pop(); | |
} | |
this.peek = function() { | |
return items[items.length-1]; | |
} | |
this.isEmpty = function() { | |
return items.length == 0; | |
} | |
this.size = function() { | |
return items.length; | |
} | |
this.clear = function() { | |
items = []; | |
} | |
this.print = function() { | |
console.log(items.toString()); | |
} | |
} | |
function baseConverter(decNumber, base) { | |
var remainderStack = new Stack(), | |
remainder, | |
baseString = '', | |
digits = '0123456789ABCDEF'; | |
while (decNumber > 0) { | |
remainder = Math.floor(decNumber % base); | |
remainderStack.push(remainder); | |
decNumber = Math.floor(decNumber / base); | |
} | |
while (!remainderStack.isEmpty()) { | |
baseString += digits[remainderStack.pop()]; | |
} | |
return baseString; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment