2019-01-19

作者: ruicore | 来源:发表于2019-01-19 19:50 被阅读0次
LeetCode 190. Reverse Bits.jpg

LeetCode 190. Reverse Bits

Description

Example 1:

Input: 00000010100101000001111010011100
Output: 00111001011110000010100101000000
Explanation: The input binary string 00000010100101000001111010011100 represents the unsigned integer 43261596, so return 964176192 which its binary representation is 00111001011110000010100101000000.
Example 2:

Input: 11111111111111111111111111111101
Output: 10111111111111111111111111111111
Explanation: The input binary string 11111111111111111111111111111101 represents the unsigned integer 4294967293, so return 3221225471 which its binary representation is 10101111110010110010011101101001.

描述

颠倒给定的 32 位无符号整数的二进制位。

示例 1:

输入: 00000010100101000001111010011100
输出: 00111001011110000010100101000000
解释: 输入的二进制串 00000010100101000001111010011100 表示无符号整数 43261596,
因此返回 964176192,其二进制表示形式为 00111001011110000010100101000000。
示例 2:

输入:11111111111111111111111111111101
输出:10111111111111111111111111111111
解释:输入的二进制串 11111111111111111111111111111101 表示无符号整数 4294967293,
因此返回 3221225471 其二进制表示形式为 10101111110010110010011101101001。

思路

  • 题目使用位运算,我们按位遍历给定的数字,如果是“1”我们就在结果中置1,否则置为0.
# -*- coding: utf-8 -*-
# @Author:             何睿
# @Create Date:        2019-01-19 18:17:49
# @Last Modified by:   何睿
# @Last Modified time: 2019-01-19 19:30:51


class Solution:
    # @param n, an integer
    # @return an integer
    def reverseBits(self, n):
        if not n: return 0
        res = 0
        for _ in range(32):
            # 左移一位,腾出位置存储将要存储的结果
            res <<= 1
            if n & 1: res += 1
            # 右移一位
            n >>= 1
        return res

源代码文件在这里.
©本文首发于何睿的博客,欢迎转载,转载需保留文章来源,作者信息和本声明.

相关文章

网友评论

    本文标题:2019-01-19

    本文链接:https://www.haomeiwen.com/subject/edwzdqtx.html