Reverse Bits

题目如下:

Reverse bits of a given 32 bits unsigned integer.

For example, given input 43261596 (represented in binary as 00000010100101000001111010011100), return 964176192 (represented in binary as00111001011110000010100101000000).

Follow up:
If this function is called many times, how would you optimize it?

var reverseBits = function(n) {
    var bStr = (n).toString(2);
    var fillBit = 32 - bStr.length;
    for (var bit = 0; bit < fillBit; bit++) {
        bStr = '0' + bStr;
    }
    // console.log(bStr);
    //javascript字符串一旦被创建,就无法更改,企图交换字符串中的字符是无法完成的!!!
    var bResult = ""; //存储取反后的32位二进制字符串
    for (var i = 0, j = bStr.length - 1; i < 32 ; j--,i++) {
        bResult = bResult + bStr.charAt(j);
    }
    return parseInt(bResult, 2);
};


你可能感兴趣的:(javascript,leetcode)