-
题目描述:
-
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.
-
样例输入:
-
1315
-
样例输出:
-
2(2(2+2(0))+2)+2(2(2+2(0)))+2(2(2)+2(0))+2+2(0)
本题从输出的结果就可以看出来,这是一道递归的例子。对于当前的数,先确定它在2^i次方左右,这里的i先确定下来,即使得2^i<=n成立的最大的i,然后继续求n-pow(2,i),直到n=0对于指数,也是同样的代码,只不过这里要注意的是,递归的出口,当指数为0,为1,为2时,作为最基本的情况,要单独列出。
#include <iostream> #include <math.h> using namespace std; void present(int n){ if(n == 0) cout<<"0"; if(n == 1){ return; } if(n == 2){ cout<<"2"; return; } int i = 0; int j = 0; while(n){ for(i=0;i<18;i++){ if(pow(2,i) > n) break; } j = i - 1; if(j!=1) cout<<"2("; else cout<<"2"; present(j); if(j!=1) cout<<")"; n -= pow(2,j); if(n != 0) cout<<"+"; } } int main(){ int n; while(cin>>n){ present(n); cout<<endl; } return 0; }