用 C++ 编写一个高效的 C 程序来反转一个数字的位
在这个问题中,我们得到一个无符号整数 n。我们的任务是创建一个程序,返回通过反转该数字所有位而生成的数字。
我们举一个例子来理解这个问题,
输入
n = 1
输出
2147483648
解释
binary of 1 is 000...0001, the reverse is 100...0000.
为了解决这个问题,我们的简单解决方案将使用一个简单的公式。我们将循环遍历该数字的二进制。并且找到该数字中设置的位的位置,假设是 i。将使用以下公式计算结果:((total_number_of_bits) - 1) - i
程序显示该算法的实现,
示例
#include<iostream> using namespace std; unsigned int reverseBitNumber(unsigned int num) { unsigned int totalNumberOfBits = sizeof(num) * 8; unsigned int reverseNumber = 0, temp; for (int i = 0; i < totalNumberOfBits; i++){ if((num & (1 << i))) reverseNumber |= (1 << ((totalNumberOfBits - 1) - i)); } return reverseNumber; } int main() { unsigned int n = 21; cout<<"The number is "<<n<<endl; cout<<"The number which has reverse bits of the number is :"<<reverseBitNumber(n); return 0; }
输出
The number is 2 The number which has reverse bits of the number is :2818572288
方法 2
另一种方法是使用移位,我们将移位该数字的位,直到它变为零,然后将其移位回反向数字,然后将位移回剩余次数以获得结果。
程序显示我们解决方案的实现,
示例
#include<iostream> using namespace std; unsigned int reverseBitNumber(unsigned int n){ unsigned int rem_shift = sizeof(n) * 8 - 1; unsigned int reverseNubmer = n; n >>= 1; while(n){ reverseNubmer <<= 1; reverseNubmer |= n & 1; n >>= 1; rem_shift--; } reverseNubmer <<= rem_shift; return reverseNubmer; } int main(){ unsigned int n = 21; cout<<"The number is "<<n<<endl; cout<<"The number which has reverse bits of the number is :"<<reverseBitNumber(n); return 0; }
输出
The number is 21 The number which has reverse bits of the number is :2818572288
广告