February 19, 2024

Viiisit [LeetCode] - 190. Reverse Bits

#php#javascript#ruby

keep learning, keep coding!

Problem - Reverse Bits

Reverse bits of a given 32 bits unsigned integer.

Note:
Note that in some languages, such as Java, there is no unsigned integer type. In this case, both input and output will be given as a signed integer type. They should not affect your implementation, as the integer’s internal binary representation is the same, whether it is signed or unsigned.
In Java, the compiler represents the signed integers using 2’s complement notation. Therefore, in Example 2 above, the input represents the signed integer -3 and the output represents the signed integer -1073741825.

翻譯蒟蒻

將給定整數的二進制表示中的位元順序完全反轉。



Solution - JavaScript

Solution 1 (wrong):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
/**
* @param {number} n - a positive integer
* @return {number} - a positive integer
*/
var reverseBits = function(n) {
let ans = 0;
for (let i = 0; i < 32; i++) {
// 將 ans 左移一位,然後加上 n 的最低位元
ans = (ans << 1) + (n & 1);
// 將 n 右移一位,丟棄已經處理過的最低位元
n = n >> 1;
}

return ans;
};

在 JavaScript 中的位元運算符對於無符號整數和有符號整數的處理方式不同。在 JavaScript 中,所有的整數都是以 64 位雙精度浮點數(double-precision floating-point)的形式存儲的。當使用位元運算符時,JavaScript 會將整數隱式轉換為 32 位有符號整數進行操作,在對無符號整數進行位元反轉時,可能會產生負數的情況。而在 JavaScript 中,對於右移運算符(>>)來說,如果操作的是一個負數,則會在左邊填充 1,這會導致結果不正確。

修正如下:

Solution 1 (correct):

1
2
3
4
5
6
7
8
var reverseBits = function(n) {
let ans = 0;
for (let i = 0; i < 32; i++) {
ans = (ans << 1) + (n & 1);
n = n >>> 1; // 使用無符號右移運算符
}
return ans >>> 0; // 返回無符號整數
};

Solution 2:

1
2
3
4
5
6
7
8
9
10
11
12
/**
* @param {number} n - a positive integer
* @return {number} - a positive integer
*/
var reverseBits = function(n) {
let binary = n.toString(2);
while (binary.length < 32) {
binary = '0' + binary;
}
let reversed = binary.split('').reverse().join('');
return parseInt(reversed, 2);
};

Solution - Ruby

1
2
3
def reverse_bits(n)
n.to_s(2).rjust(32, '0').reverse.to_i(2)
end

Ruby 方法筆記

1
2
"hello".rjust(10)         # => "     hello"
"hello".rjust(10, '123') # => "12312hello"

Solution - PHP

1
2
3
4
5
6
7
8
function reverseBits($n) {
$ans = 0;
for ($i = 0; $i < 32; $i++) {
$ans = ($ans << 1) | ($n & 1);
$n >>= 1;
}
return $ans;
}

在 PHP 中,位元運算符(>><<)會自動地處理無符號整數。表示即使操作的是無符號整數,也不會在左邊填充 1。因此,不需要像在 JavaScript 中一樣使用無符號右移運算符(>>>)。

LeetCode 傳送門 - Reverse Bits