jithin surendran
jithin surendran

Reputation: 45

Recursive function to find binary not returning elements in single array. (Not pushing to the same )

Problem statement: I'm trying to get string > binary without using the inbuilt method in javascript.

This is a piece of program where a string input (like "ABC") is accepted, then it is translated to an array of equivalent code value ([65,66,67]).

Function binary() will change a number to binary. But I'm unable to join them together to loop through all the contents. Please help. (I'm a noob, please forgive my bad code and bad explanation)

var temp3 = [65,66,67];
var temp2 = [];
var r;

for(i=0;i<temp3.length;i++) {
var  r = temp3[i];    
temp2.push(binary(r));
}

function binary(r) {
  if (r === 0) return;
  temp2.unshift(r % 2);
  binary(Math.floor(r / 2));
  return temp2;
}
console.log(temp2);

Upvotes: 0

Views: 67

Answers (2)

Scott Sauyet
Scott Sauyet

Reputation: 50787

I think this is a cleaner version of this function. It should work for any non-negative integers, and would be easy enough to extend to the negatives. If we have a single binary digit (0 or 1) and hence are less than 2, we just return the number converted to a string. Otherwise we call recursively on the floor of half the number (as yours does) and append the final digit.

const binary = (n) =>
  n < 2
    ? String (n)
    : binary (Math.floor (n / 2)) + (n % 2)
    
console.log (binary(22)) //=> '10110'

console.log ([65, 66, 67] .map (binary)) //=> ['1000001', '1000010', '1000011']

Upvotes: 2

Optiq
Optiq

Reputation: 3182

In your function you have this code

var  r = temp3[i];

I don't see any temp3 variable anywhere in your code above so I'd imagine that could be causing some issues.

Upvotes: 0

Related Questions