8758:2的幂次方表示
总时间限制:
1000ms
内存限制:
65536kB
描述
任何一个正整数都可以用2的幂次方表示。例如:
137=27+23+20
同时约定方次用括号来表示,即ab可表示为a(b)。由此可知,137可表示为:
2(7)+2(3)+2(0)
进一步:7=22+2+20(21用2表示)
3=2+20
所以最后137可表示为:
2(2(2)+2+2(0))+2(2+2(0))+2(0)
又如:
1315=210+28+25+2+1
所以1315最后可表示为:
2(2(2+2(0))+2)+2(2(2+2(0)))+2(2(2)+2(0))+2+2(0)
输入
一个正整数n(n≤20000)。
输出
一行,符合约定的n的0,2表示(在表示中不能有空格)。
样例输入
137
样例输出
2(2(2)+2+2(0))+2(2+2(0))+2(0)
解题思路:
一个数,怎么递归求呢?
你先求小于等于这个数最大的 2^x次方 用n 减去 2^x此法,继续用这个思路求,
比如说137 = 2 (7) + 2(3) + 2(0)
然后 7 也可以用同样的方式去求。
3 也一样,
这样就想到了递归,
#include<iostream>
#include<cstring>
using namespace std;
string DFS(int n){
if(n == 1) return "2(0)";
if(n == 2) return "2";
int m = 1;
int e = 0;
while(m <= n) {
m *= 2;
e++;
}
m /= 2;
e--;
string h;
if(m == 2)
h += "2";
else
h += "2(" + DFS(e) + ")";
if(m == n)
return h;
h += "+" + DFS(n-m);
return h;
}
int main(){
int n;
cin >> n;
cout << DFS(n) << endl;
return 0;
}
另一种递归
#include<iostream>
#include<cstring>
using namespace std;
void DFS(int n){
if(n == 1) {
cout << "2(0)";
return ;
}
if(n == 2){
cout << "2" ;
return ;
}
int m = 1;
int e = 0;
while(m <= n) {
m *= 2;
e++;
}
m /= 2;
e--;
if(e == 1)
cout << "2" ;
else{
cout << "2(" ;
DFS(e);
cout << ")";
}
if( n - m == 0)
return;
else{
cout << "+" ;
DFS(n - m);
}
}
int main(){
int n;
cin >> n;
DFS(n) ;
return 0;
}