2025-06-26 23:36:36 +08:00

26 lines
593 B
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* @param {number} n - a positive integer
* @return {number} - a positive integer
*/
/**
* @param {number} n - a positive integer
* @return {number} - reversed bits result
*/
const reverseBits = function (n) {
let res = 0;
// 一共处理32位
for (let i = 0; i < 32; i++) {
// 提取最低位0或1
const bit = n & 1;
// 把结果左移一位为新加入的bit腾位置
res = (res << 1) | bit;
// 原数字右移一位(无符号),处理下一位
n >>>= 1;
}
return res >>> 0; // 确保返回的是无符号数(防止变负)
};