C ++中要求和的2的幂
在这个问题中,我们得到一个整数N。我们的任务是打印数字,将其提高到2的幂时,将得出该数字。
让我们以一个例子来了解问题
输入-17
输出-0,4
说明-17=24+20=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
热门推荐
10 新年门口花束祝福语简短
11 盘锦结婚祝福语大全简短
12 父母生日祝福语 简短独特
13 家庭恩爱祝福语简短英文
14 高考俄语祝福语大全简短
15 虎年祝福语 诗句唯美简短
16 生日婚礼祝福语简短精辟
17 虎年喝酒拜年祝福语简短
18 教师闺蜜祝福语简短