Reverse Bits
Time Limit: 2000/1000ms (Java/Others)
Problem Description:
Reverse bits of a given 32 bits signed integer.For example, given input 43261596 (represented in binary as 00000010100101000001111010011100), return 964176192 (represented in binary as 00111001011110000010100101000000).
Input:
The input includes several cases. For each case,input a 32-bits signed integer.
Output:
For each case,output the answer.
Sample Input:
43261596
Sample Output:
964176192
解题思路:简单地将二进制转化成十进制。如果n是负数,先将其转化成正数,取反后再加1,但是有一种特殊情况需要特判,即n==-2147483648(1<<31)由于取n的绝对值之后会溢出int最大值2147483647,因此需要单独判断这种情况,其二进制反转之后的结果为1。
AC代码一之简单模拟:
1 #include<bits/stdc++.h> 2 using namespace std; 3 int main(){ 4 int n,m,k,tmp,base,d[32]; 5 while(cin>>n){ 6 if(n==(1<<31)){cout<<1<<endl;continue;}//特判:n==-2147483648反转32位二进制后结果为1 7 memset(d,0,sizeof(d));k=0;tmp=base=1;m=n; 8 if(m<0)m=-n; 9 while(m){d[k++]=m%2;m/=2;}//取余操作 10 if(n<0){//如果n小于0,将n取反再加1 11 for(int i=0;i<32;++i){ 12 d[i]=((d[i]==1?0:1)+tmp)%2;//按位取反,tmp初始值为1 13 tmp=((d[i]==1?0:1)+tmp)/2; 14 } 15 } 16 for(int i=31;i>=0;--i){ 17 if(d[i])m+=base;//从高位向低位计算,相当于反转32位二进制之后从低位向高位计算 18 base*=2; 19 } 20 cout<<m<<endl; 21 } 22 return 0; 23 }
AC代码二之'且'运算符的巧妙使用:从第0位到第31位,有1就取。
1 #include<bits/stdc++.h> 2 using namespace std; 3 int main(){ 4 int n,m; 5 while(cin>>n){m=0; 6 for(int i=0;i<32;++i) 7 if(n&(1<<i))m+=(1<<(31-i));//如果二进制的第i位上为1,则加上2^(31-i) 8 cout<<m<<endl; 9 } 10 return 0; 11 }