intToBinaryString.js 540 B

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