ในปัญหานี้ เราได้รับตัวเลข 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