convert a number from base 10 to base 2 in typescript

To convert a number from base 10 to base 2 (binary) in TypeScript, you can use the following algorithm:

  1. Create an empty array to store the binary digits.
  2. Divide the decimal number by 2.
  3. Store the remainder (either 0 or 1) in the array.
  4. Repeat steps 2 and 3 until the decimal number is 0.
  5. Reverse the order of the digits in the array to get the binary representation.

Here's the TypeScript code:

index.ts
function decimalToBinary(decimal: number): string {
  let binaryDigits: number[] = [];
  while (decimal > 0) {
    let remainder = decimal % 2;
    binaryDigits.push(remainder);
    decimal = Math.floor(decimal / 2);
  }
  return binaryDigits.reverse().join("");
}
265 chars
10 lines

This function takes a decimal number as input and returns a string representing the binary equivalent.

gistlibby LogSnag