Implementation (split,reverse,number->bitString, lead zero) of JavaScript solution here


  • 0
    Z
    /**
     * @param {number} n - a positive integer
     * @return {number} - a positive integer
     */
    var reverseBits = function(n) {
        // let b = (n.toString('2', n)).split('').reverse();
        let b = (n.toString(2)).split('').reverse();
        // num->2string->split+reverse +++++++++++implementation here++++++++++++
        // let b = new Array(0);while(n>0){if(n&1){b.push('1');n=(n-1)/2;}else{b.push('0');n = n/2;}}
        // split here  +++++++++++implementation here++++++++++++
        // let b = new Array(0); while(b.length<n.length){b.push(n.charAt(b.length));} b = b.reverse();
        // reverse here  +++++++++++implementation here++++++++++++
        // let l = 0, r = b.length - 1, t; while(l<r){t= b[l];b[l]= b[r];b[r]=t;l++;r--;}
        // reconstruct here  +++++++++++implementation here++++++++++++
        // b = b.concat('000000000000000000000000000000000000000000').join('').substr(0,32);
        // reconstruct 2 here  +++++++++++implementation here++++++++++++
        // while (b.length < 32) b.push('0');
        return (parseInt((b.join('') + '00000000000000000000000000000000000000000000000000000').substr(0,32), '2')); 
    };
    

    Unfortunately, I didn't implement the last part which converts 32-length binary string to big number. I hope some master of JavaScript here can show me the solution of implementation. Thank! ^-^


  • 0
    Z

    Actual solution is only two lines base on the interfaces of JavaScript.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.