intToBinaryString.js 498 B

123456789101112131415161718192021
  1. 'use strict';
  2. var $floor = require('math-intrinsics/floor');
  3. // https://runestone.academy/ns/books/published/pythonds/BasicDS/ConvertingDecimalNumberstoBinaryNumbers.html#:~:text=The%20Divide%20by%202%20algorithm,have%20a%20remainder%20of%200
  4. module.exports = function intToBinaryString(x) {
  5. var str = '';
  6. var y;
  7. while (x > 0) {
  8. y = x / 2;
  9. x = $floor(y); // eslint-disable-line no-param-reassign
  10. if (y === x) {
  11. str = '0' + str;
  12. } else {
  13. str = '1' + str;
  14. }
  15. }
  16. return str;
  17. };