Interview string completion



Converts the given number to a binary string. If the length of the string is less than 8 bits, 0 will be filled to the full 8 bits.







Mode 1 uses the cycle to fill the left zero

function convertToBinary(num) {
    var str = num.toString(2);
    while(str.length < 8) {
        str = "0" + str;
    return str;

Mode 2 fixed length zero compensation slice

function convertToBinary(num) {
  return ('00000000' + num.toString(2)).slice(-8);

Mode 3: calculate first and then fill in

function convertToBinary(num) {
    var str = num.toString(2);
    return "0".repeat(8 - str.length) + str;

For es8 +, mode 4 can be done in one line

function convertToBinary(num) {
    return num.toString(2).padStart(8,"0")


Mode 1 costs a little bit more memory than mode 2, because it keeps generating new variables.
The last one needs high version JS support, which is simple and direct.

This work adoptsCC agreementReprint must indicate the author and the link of this article

Recommended Today

Implementation example of go operation etcd

etcdIt is an open-source, distributed key value pair data storage system, which provides shared configuration, service registration and discovery. This paper mainly introduces the installation and use of etcd. Etcdetcd introduction etcdIt is an open source and highly available distributed key value storage system developed with go language, which can be used to configure sharing […]