LeetCode 190. 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 as 00111001011110000010100101000000).

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

翻譯

給一個32 bits的int整數,反轉整數的bits。

範例: 整數43261596 轉換成bits = 00000010100101000001111010011100,將bit反轉00111001011110000010100101000000再轉成整數964176192回傳

進階:
如果這個function會被呼叫很多次,要怎麼做最佳化?

思路

用除法將十進位數字轉換成二進位數字,也就是bits,將轉換後的二進位數字反轉,再轉回整數。

解題

/**
 * @param {number} n - a positive integer
 * @return {number} - a positive integer
 */
var reverseBits = function(n) {
    if(n == 0) return 0;
    // 用一個list將n轉為2進位的bits array
    var list = [];

    for(var i = 0 ; i < 32 ; i++){
        if(n > 0){
            // 從低位數開始轉換為2進位,放進list時就已經完成反轉的動作
            // ex. 6轉換為2進位為110 ( 6 => 6%2 = 0 , 3%2 = 1 , 1%2 =1 ) 
            list.push(parseInt(n%2));
            n = parseInt(n/2);
        } else {
            list.push(0);
        }
    }

    // 將bits array轉換成整數回傳
    return parseInt(list.join(""),2);
};

results matching ""

    No results matching ""