C++ 中首三位和末三位比特
在这个问题中,我们给定一个数字 N。我们的任务是找到给定整数 N 的前三位和后三位比特的十进制转换。
让我们举一个例子来理解这个问题,
Input : 57 Output : 71
解决方案方法
一个简单的解决方案是将数字 n 转换为其二进制等效值,然后将比特存储在一个数组中。之后,我们将分别将数组中的前三位和后三位转换为数字。这两组比特的十进制转换就是我们的结果。
例如,取数字 80。
80 的二进制转换是 1010000。
前三位 (101) 的十进制转换是 5。
后三位 (000) 的十进制等效值为 0。
因此输出为 5 0。
示例
程序说明我们解决方案的工作原理
#include <bits/stdc++.h>
using namespace std;
void convtbnTodcml(int n)
{
int arr[64] = { 0 };
int x = 0, index;
for (index = 0; n > 0; index++) {
arr[index] = n % 2;
n /= 2;
}
x = (index < 3) ? 3 : index;
int d = 0, p = 0;
for (int index = x - 3; index < x; index++)
d += arr[index] * pow(2, p++);
cout << d << " ";
d = 0;
p = 0;
for (int index = 0; index < 3; index++)
d += arr[index] * pow(2, p++);
cout << d;
}
int main()
{
int n = 57;
cout<<"Decimal conversion of first and last bits of the number "<<n<<" is ";
convtbnTodcml(n);
return 0;
}输出
Decimal conversion of first and last bits of the number 57 is 7 1
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP