在这个问题中,我们得到一个整数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