本文主要是介绍leetcod--Reverse Bits,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
题目描述:
everse bits of a given 32 bits unsigned integer.
For example, given input 43261596 (represented in binary as 00000010100101000001111010011100), return 964176192 (represented in binary as00111001011110000010100101000000).
Follow up:
If this function is called many times, how would you optimize it?
Related problem: Reverse Integer
Credits:
Special thanks to @ts for adding this problem and creating all test cases.
解题思路:
将一个整形数的二进制序列逆转,后输出二进制序列代表的十进制数
方法一:
采用一个32长度的数组,存储二进制,之后逆转,再计算此数组所表示的整形数。
class Solution {
public:uint32_t reverseBits(uint32_t n) {vector<int> a(32,0);int mood=0,i=0,temp;unsigned int temp1=0;while(n/2!=0){mood=n%2;a[i]=mood;n/=2;i++;}a[i]=n%2;reverse(a.begin(),a.end());for(int j=0;j<32;j++){if (a[j]!=0){temp=pow(2*1.0,j);temp1+=temp;}}return temp1;}
};
方法二:
class Solution {
public:uint32_t reverseBits(uint32_t n) {uint32_t bin=0;for (int i = 0; i < 32; i++) bin+=(n >> i & 1)<<(31-i);return bin;}
};
这篇关于leetcod--Reverse Bits的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!