题解 | #2的幂次方#
2的幂次方
http://www.nowcoder.com/practice/7cf7b0706d7e4b439481f53e5fdac6e7
递归很强大。
#include <cstdio>
#include <iostream>
using namespace std;
void Int2Str(int x, string &s){
if(x == 0 || x == 2){
s.push_back('0'+x);
return;
}
int index = 0;
int tag = 0;//本子域输出过,需要输出加号 的标记
while(x){
if(x%2){
if(tag){
s.push_back('+');
}
tag = 1;
if(index != 1){
s.push_back(')');
Int2Str(index, s);
s.push_back('(');
}
s.push_back('2');
}
x /= 2;
index++;
}
}
int main(){
string s;
int x;
while(scanf("%d",&x) != EOF){
Int2Str(x, s);
for(int i=s.size()-1; i>=0; i--){
printf("%c",s[i]);
}
printf("\n");
s.clear();
}
return 0;
}