tailgo / poorguy-fly

1 stars 0 forks source link

190. 颠倒二进制位(简单) - https://leetcode-cn.com/problems/reverse-bits/ #17

Open tailgo opened 5 years ago

tailgo commented 5 years ago

https://leetcode-cn.com/problems/reverse-bits/

看到题目第一反应就是反转字符串。于是就 js 语言特性一句话搞定。

执行用时 : 112 ms, 在Reverse Bits的JavaScript提交中击败了94.12% 的用户 内存消耗 : 35.9 MB, 在Reverse Bits的JavaScript提交中击败了43.53% 的用户

/**
 * @param {number} n - a positive integer
 * @return {number} - a positive integer
 */
var reverseBits = function(n) {
    return parseInt(n.toString(2).padStart(32, '0').split('').reverse().join(''), 2)
};
tailgo commented 5 years ago

其次是按位拷贝,比较简单就不想写了。 翻阅算法,有个很骚气的玩意。太骚了找不到原理很难受。

https://stackoverflow.com/questions/746171/most-efficient-algorithm-for-bit-reversal-from-msb-lsb-to-lsb-msb-in-c