LeetCode 190. Reverse Bits [Swift 题解]

题目

Reverse bits of a given 32 bits unsigned integer.

Example:

Input: 43261596  
Output: 964176192  
Explanation: 43261596 represented in binary as 00000010100101000001111010011100,  
             return 964176192 represented in binary as 00111001011110000010100101000000.

思路

相对简单的位运算题目, 需要注意的是题目要求的是32bit, 所以每次把原数字往右移一位,然后放到result里。

class Solution {  
    func reverse(_ num: Int) -> Int {
        var copy = num
        var result = 0
        var index = 32
        while index > 0 {
            let bit = copy & 1
            copy = copy >> 1
            result = result << 1
            result += bit

            index -= 1
        }

        return result
    }
}

chenbo

编程爱好者

Singapore