javascript - Need help writing code to convert decimal to binary without the use of the toString -
i'm trying create own decimal binary converter method of decrementing inputted variable (decimal value), dividing 2 , storing remainder (like 2nd grade math remainder), either 0 or 1. each of remainder values thin should stored in array , think maybe put in backwards significant digit first in array (this because when decrementing remainer values filled in left right). soooo yea dont know how store remainder values in array using function in advance , if confusing feel free ask because im not sure if best method of doing came with
function decimaltobinary(num) { var bin = 0; while (num > 0) { bin = num % 2 + bin; num >>= 1; // /= 2 without remainder if } alert("that decimal in binary " + bin); }
your code correct. main problem bin
starts out 0
; when add digit, added numerically, code ends counting binary 1
s: in manner, 10
initial 0
, , +1+0+1+0
, resulting in 2
. want handle string: ""+1+0+1+0
results in 1010
. so, needed change is:
var bin = "";
if want solve using arrays, minimal changes code, be:
function decimaltobinary(num) { var bin = []; while (num > 0) { bin.unshift(num % 2); num >>= 1; // /= 2 without remainder if } alert("that decimal in binary " + bin.join('')); }
here, use .unshift
add element head of array (and renumbering remaining elements); .join()
collect them string.
or this:
function decimaltobinary(num) { var bin = []; while (num > 0) { bin[bin.length] = num % 2; num >>= 1; // /= 2 without remainder if } alert("that decimal in binary " + bin.reverse().join('')); }
this not good, illustrates more things can arrays: taking length, setting arbitrary element, , flipping them around.
Comments
Post a Comment