ในปัญหานี้ เราได้รับจำนวนเต็ม N หน้าที่ของเราคือพิมพ์ตัวเลขซึ่งเมื่อยกกำลัง 2 ให้ตัวเลขนั้นขึ้น
มาดูตัวอย่างทำความเข้าใจปัญหากัน
ป้อนข้อมูล − 17
ผลผลิต − 0, 4
คำอธิบาย − 17 =2 4 + 2 0 =16 + 1
เพื่อแก้ปัญหานี้ เราจะหารตัวเลขด้วย 2 ซ้ำๆ ด้วยวิธีนี้ ทุกตัวเลขสามารถแสดงเป็นกำลัง 2 วิธีนี้ใช้เพื่อแปลงตัวเลขให้เทียบเท่ากับเลขฐานสอง
ตัวอย่าง
โปรแกรมแสดงการใช้งานโซลูชันของเรา
#include <bits/stdc++.h>
using namespace std;
void sumPower(long int x) {
vector<long int> powers;
while (x > 0){
powers.push_back(x % 2);
x = x / 2;
}
for (int i = 0; i < powers.size(); i++){
if (powers[i] == 1){
cout << i;
if (i != powers.size() - 1)
cout<<", ";
}
}
cout<<endl;
}
int main() {
int number = 23342;
cout<<"Powers of 2 that sum upto "<<number<<"are : ";
sumPower(number);
return 0;
} ผลลัพธ์
Powers of 2 that sum upto 23342are : 1, 2, 3, 5, 8, 9, 11, 12, 14