C++ 中的前三位和后三位
c++server side programmingprogramming更新于 2025/5/31 11:52:17
在这个问题中,我们给定一个数字 N。我们的任务是找到给定整数值 N 的前三位和后三位的十进制转换。
让我们举一个例子来理解这个问题,
输入:57 输出: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