admin管理员组

文章数量:1287514

I just had an interview question, where I need to get the binary representation of an integer, this is something I should know how to do.. for example, 5 is represented in binary as 101, and the steps look something like:

// 5 % 2 = 1
// 5 / 2 = 2
// result = 1;

// 2 % 2 = 0
// 2 / 2 = 1
// result = 10

// 1 % 2 = 1
// 1 / 2 = 0
// result = 101

the stopping condition is when ~~(1/2) === 0

so I have this:

const getBinary = (v) => {

  let remainder, binary = 1;

  while (true) {

    remainder = v % 2;
    v = ~~(v / 2);

    if (v === 0) {
      return binary;
    }

    if (remainder === 0) {
      binary = binary * 10 + 1;
    }
    else {
      binary = binary * 10;
    }
  }

};

console.log(getBinary(5));

so that works, but the binary variable is initialized to 1. Is there a way to improve this so it works with negative numbers, or if 0 is passed as the argument to the function?

I just had an interview question, where I need to get the binary representation of an integer, this is something I should know how to do.. for example, 5 is represented in binary as 101, and the steps look something like:

// 5 % 2 = 1
// 5 / 2 = 2
// result = 1;

// 2 % 2 = 0
// 2 / 2 = 1
// result = 10

// 1 % 2 = 1
// 1 / 2 = 0
// result = 101

the stopping condition is when ~~(1/2) === 0

so I have this:

const getBinary = (v) => {

  let remainder, binary = 1;

  while (true) {

    remainder = v % 2;
    v = ~~(v / 2);

    if (v === 0) {
      return binary;
    }

    if (remainder === 0) {
      binary = binary * 10 + 1;
    }
    else {
      binary = binary * 10;
    }
  }

};

console.log(getBinary(5));

so that works, but the binary variable is initialized to 1. Is there a way to improve this so it works with negative numbers, or if 0 is passed as the argument to the function?

Share Improve this question asked Aug 29, 2018 at 22:47 Alexander MillsAlexander Mills 100k166 gold badges534 silver badges910 bronze badges 3
  • 1 this is not quite right. For 10 it returns 1101 – Jeremy Kahan Commented Aug 29, 2018 at 23:01
  • yep maybe so, looking for something that is correct – Alexander Mills Commented Aug 29, 2018 at 23:06
  • Should the negatives be using two's pliment, one's pliment or just a - sign in front of the binary representation? – ibrahim mahrir Commented Aug 29, 2018 at 23:29
Add a ment  | 

4 Answers 4

Reset to default 7
var integer = 52;
console.log(integer.toString(2));

Simple function native to javascript, no lengthy code required.

If you want to write it from scratch you can use something like this:

function toBinary(n) {
    n = Number(n);
    if (n == 0) return '0';
    var r = '';
    while (n != 0) {
        r = ((n&1)?'1':'0') + r;
        n = n >>> 1;
    }
    return r;
}
console.log(toBinary(5));
console.log(toBinary(10));
console.log(toBinary(-5));
console.log(toBinary(0));

So here is one way. It has an inner function that handles the basics and an outer one that extends to your special cases. I preferred to do string representations.

const getBinary = v => {
   if (v === 0) return '';
   let remainder = v % 2;
   let quotient = (v - remainder) / 2;
   if (remainder === 0) {
      return getBinary(quotient) + '0';
   }
   else {
      return getBinary(quotient) + '1';
   }
}

const betterGetBinary = v => {
   if (v === 0) return '0';
   if (v < 0) return '-' + getBinary(-v);
   return getBinary(v);
}

console.log(betterGetBinary(-10));

A quick and dirty solution, although it 'might' have two flaws:
- Math.floor()
- no bitwise operator

let getBinary = number => {
  let done = false;
  let resultInverted = [];
  let acc = number;
  while (!done) {
    let reminder = acc % 2;
    if (acc === 1) {
      done = true;
    }
    acc = Math.floor(acc / 2);
    resultInverted.push(reminder);
  }
  return Number(resultInverted.reverse().join(''));
};

console.log(typeof getBinary(2));
console.log(getBinary(5));
console.log(getBinary(127));

本文标签: javascriptGet binary representation of integerStack Overflow