190. Reverse Bits(python+cpp)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_21275321/article/details/83823444

题目:

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. 

Follow up:
If this function is called many times, how would you optimize it?

解释:
数字转换成二进制以后,前面补0直至一共有32bit,之后再逆序翻转即可。
python代码:

class Solution:
    # @param n, an integer
    # @return an integer
    def reverseBits(self, n):
        return int((bin(n)[2:]).zfill(32)[::-1],2)

c++代码:

 class Solution {
public:
    uint32_t reverseBits(uint32_t n) {
        string bin_n=dec2bin(n);
        reverse(bin_n.begin(),bin_n.end());
        return bin2dec(bin_n);
    }
    string dec2bin(uint32_t n)
    {
        string result="";
        while(n)
        {
            result=to_string(n%2)+result;
            n/=2;
        }
        string zeros(32-result.size(),'0');
        return zeros+result;
    }
    uint32_t bin2dec(string s)
    {
        int base=1;
        int result=0;
        for (int i=s.size()-1;i>=0;i--)
        {
            result+=base*(s[i]-'0');
            base*=2;
        }
        return result;
    }    
};

总结:
二进制和十进制的相互转换的写法要烂熟于心。

猜你喜欢

转载自blog.csdn.net/qq_21275321/article/details/83823444