Try   HackMD

leetcode解題:(Easy) 190. Reverse Bits

題目:https://leetcode.com/problems/reverse-bits/

描述:將32位元的unsigned int中的位元順序顛倒後回傳結果的值

解題思路:詳細解答來源,用分治法(divide and conquer)每次將處理範圍中左半與右半邊的位元值互換,對一個有2^n位元的數字總共只需要換n次即可

程式碼:

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