题目描述
Every positive number can be presented by the exponential form.For example, 137 = 2^7 + 2^3 + 2^0。 Let's present a^b by the form a(b).Then 137 is presented by 2(7)+2(3)+2(0). Since 7 = 2^2 + 2 + 2^0 and 3 = 2 + 2^0 , 137 is finally presented by 2(2(2)+2 +2(0))+2(2+2(0))+2(0). Given a positive number n,your task is to present n with the exponential form which only contains the digits 0 and 2.
输入描述:
For each case, the input file contains a positive integer n (n<=20000).
输出描述:
For each case, you should output the exponential form of n an a single line.Note that,there should not be any additional white spaces in the line.
示例1
输入
1315
输出
2(2(2+2(0))+2)+2(2(2+2(0)))+2(2(2)+2(0))+2+2(0)
#include <iostream>
#include <cmath>
#include <vector>
#include <algorithm>
using namespace std;
vector<int> res;
char toChar(int n) {
return '0' + n;
}
void toBinary(int n) {
string s; // 记录二进制 (如是1,输出 2 的 index 次方) ,0 不输出
int cnt = 0;
while(n > 0) {
if (n % 2 == 1) {
cnt ++;
}
s += toChar(n % 2);
n /= 2;
}
reverse(s.begin(),s.end());
// cout << s << endl;
// 至此,s保留了二进制,并且输出
// 但是还需要按题目转化
reverse(s.begin(),s.end());
int maxIndex = s.size() - 1;
for (int i = maxIndex; i >= 0; i--) {
if(s[i] == '1') {
cout << 2 ;
if (i == 0) {
cout << "(0)" ;
} else if (i == 1) {
} else {
cout << "(";
toBinary(i);
cout << ")";
}
// 这个不想了 cnt -- > 0 或者 --cnt > 0 自己试一下
if (--cnt > 0) {
cout << "+";
}
}
}
}
int main() {
int t;
while(cin >> t) {
toBinary(t);
cout << endl;
}
}