二的冪次方(遞歸)
描述 Description
任何一個正整數都可以用2的冪次方表示。例如:
137=2^7+2^3+2^0
同時約定方次用括號來表示,即ab 可表示為a(b)。
由此可知,137可表示為:
2(7)+2(3)+2(0)
進一步:7= 2^2+2+2^0 (21用2表示)
3=2+2^0
所以最後137可表示為:
2(2(2)+2+2(0))+2(2+2(0))+2(0)
又如:
1315=2^10 +2^8 +2^5 +2+2^0
所以1315最後可表示為:
2(2(2+2(0))+2)+2(2(2+2(0)))+2(2(2)+2(0))+2+2(0)
輸入:正整數(n≤20000)
輸出:符合約定的n的0,2表示(在表示中不能有空格)
輸入格式 Input Format
一個正整數
輸出格式 Output Format
符合約定的n的0,2表示(在表示中不能有空格)
樣例輸入 Sample Input
73
樣例輸出 Sample Output
2(2(2)+2)+2(2+2(0))+2(0)
遞歸操作題,個人感覺很是麻煩,關鍵還是在於對遞歸的理解程度。
代碼:
#include <iostream>
#include <iomanip>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <ctime>
#include <algorithm>
using namespace std;
int n;
void pl(int n)
{
if(n==1) {cout<<"2(0)";return;}
else if(n==2) {cout<<‘2‘;return;}
else
{
int i=0,j=1;//以下操作,n為類似循環的邊界的存在,當j比n大的時候開始/=2,只要n-j!=0就每次都輸出加號,返回n-j;一直到j!=n時結束遞歸,其中對於i的遞歸為局部遞歸,為局部判定
while(1)
{
j*=2;
if(j>n)
{
j/=2;
if(i==1)
cout<<‘2‘;
else
{
cout<<"2(";
pl(i);
cout<<‘)‘;
}
if(n-j!=0)
{
cout<<‘+‘;
pl(n-j);
}
return;
}
else
i++;
}
}
}
int main()
{
cin>>n;
pl(n);
return 0;
}
二的冪次方(遞歸)