# leetcode解題:(Easy) 190. Reverse Bits 題目:https://leetcode.com/problems/reverse-bits/ 描述:將32位元的unsigned int中的位元順序顛倒後回傳結果的值 解題思路:[詳細解答來源](https://leetcode.com/problems/reverse-bits/solutions/1232842/java-c-0ms-o-1-time-complexity-in-place-detailed-explanation/),用分治法(divide and conquer)每次將處理範圍中左半與右半邊的位元值互換,對一個有`2^n`位元的數字總共只需要換`n`次即可 程式碼: ```JAVA= public class Solution { // you need treat n as an unsigned value public int reverseBits(int n) { //Java bit shift operartor: >> (signed right shift) //Java bit shift operartor: >>> (unsigned right shift) //Java bit shift operartor: << (unsigned/signed left shift) n = ((n & 0xffff0000) >>> 16) | ((n & 0x0000ffff) << 16); n = ((n & 0xff00ff00) >>> 8) | ((n & 0x00ff00ff) << 8); n = ((n & 0xf0f0f0f0) >>> 4) | ((n & 0x0f0f0f0f) << 4); n = ((n & 0xcccccccc) >>> 2) | ((n & 0x33333333) << 2); n = ((n & 0xaaaaaaaa) >>> 1) | ((n & 0x55555555) << 1); return n; } } ``` 時間複雜度:O(1) 空間複雜度:O(1) ###### tags: `leetcode` `easy` `bitwise operate`
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up