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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP