嘗試使用左移結果解決反向位解決方案,問題說
Reverse bits of a given 32 bits unsigned integer.
Input: n = 00000010100101000001111010011100
Output: 964176192 (00111001011110000010100101000000)
Explanation: The input binary string 00000010100101000001111010011100 represents the unsigned integer 43261596, so return 964176192 which its binary representation is 00111001011110000010100101000000.
這里在解決方案代碼回圈 32 次,然后對結果進行左移,然后 ifnum & 1大于 0 。然后i.e. its 1遞增結果并右移shift nums by 1或nums modulus 2最后回傳result
為什么輸出為0,any thoughts and updated solution for this code
let reverseBits = function(nums) {
let result = 0
for (let i = 1; i <= 32; i ) {
result <<= 1
if (nums & 1 > 0)
result
nums >>= 1
}
return result
}
console.log(reverseBits(11111111111111111111111111111101))
輸出顯示為 0
PS C:\VSB-PRO> node Fibo.js
0
uj5u.com熱心網友回復:
一些問題:
您作為引數傳遞給函式的示例值不是以二進制表示法給出的,而是以十進制表示法給出的,因此它是一個與預期不同的數字。使用
0b二進制表示法中的文字前綴。當使用
<<操作者(和=<<),JavaScript就解釋32次位為符號位。我想它不是為了產生負值,所以通過使用乘以 2 而不是移位運算子來避免這種情況。
不是問題,但是:
的
>>操作者將會對具有32個數字的特定效應第二位組:該位將被保留后移。由于您的腳本從不檢查該位,因此這不是問題,但如果移入 0 位會更自然。為此,您可以使用>>>運算子。最后,以二進制表示法輸出回傳值可能很有用,這樣您就可以更輕松地驗證結果。
let reverseBits = function(nums) {
let result = 0;
for (let i = 1; i <= 32; i ) {
// use multiplication to avoid sign bit interpretation
result *= 2;
if (nums & 1 > 0)
result ;
nums >>>= 1;
}
return result;
}
// Express number in binary notation:
let n = 0b11111111111111111111111111111101;
let result = reverseBits(n);
// Display result in binary notation
console.log(result.toString(2));
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/408223.html
標籤:
