ในปัญหานี้ เราได้รับตัวเลข N ภารกิจของเราคือ หาการแปลงทศนิยมของบิต 3 ตัวแรกและ 3 ตัวสุดท้ายสำหรับค่าจำนวนเต็ม N ที่กำหนด
มาดูตัวอย่างเพื่อเข้าใจปัญหา
Input : 57 Output : 71
วิธีการแก้ปัญหา
วิธีแก้ปัญหาแบบง่ายคือการเปลี่ยนตัวเลข n เป็นค่าเทียบเท่าทางไบนารีแล้วเก็บบิตในอาร์เรย์ หลังจากนี้ เราจะแปลงค่า 3 ตัวแรกและ 3 ตัวสุดท้ายจากอาร์เรย์เป็นตัวเลขแยกกัน การแปลงทศนิยมของทั้งสองชุดบิตคือผลลัพธ์ของเรา
ตัวอย่าง ให้ตัวเลข 80
การแปลงไบนารีของ 80 คือ 1010000
การแปลงทศนิยมของ 3 บิตแรก (101) คือ 5
ค่าเทียบเท่าทศนิยมของ 3 บิตสุดท้าย (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