牛客网 基础-2的幂次方

第1节 基础-2的幂次方

    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)

其实这道题我开始是没有思路的,137=2^7+2^3+2^0;7=2^2+2^1+2^0;3=2^1+2^0;137=2^(2(2)+2+2(0))+2(2+2(0))+2(0),将一个大数分拆成若干个2的n次方之和,很容易想到递归算法,但是我当时一直没想到.

对于一个整数n,他可以分解成2的某次幂和另外一个数的和,

即n=2^x+y,(其中x是满足2^x<=n最大的x),

这样递归结构就很清晰了,要打印f(n),

即等价于打印2(f(x))+f(y),

递归的边界条件是x==1,或x==2.例如7=2^2+3,

即f(7)=2(f(2))+f(3)=2(f(2))+f(2)+f(1)),由于f(2)和f(1)到达了边界条件,

所要可以直接打印出来,即f(2)=2,f(1)=2(0)所以f(7)=2(2)+2+2(0);代码体现出来首先第一步先找2^x<=n最大的幂,也就是while语句,接下来需要找边界条件.

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cmath>
using namespace std;
void print(int n)
{
  int i=0;
  while(pow(2,i)<=n)
  {
    i++;
  }
  i--;//break出来的i需要往回倒一下
  if(i==0)
  {
    cout<<"2(0)";
    return;
  }
  if(i==1)
  {
    cout<<"2(1)";
  }
  else
  {
    cout<<"2(";
    print(i);
    cout<<")";
  }
  if(n-pow(2,i)>0)
  {
    cout<<"+";
    print(n-pow(2,i));
  }
}
int main()
{
  int n;
  cin>>n;
  print(n);
  cout<<endl;
}

猜你喜欢

转载自blog.csdn.net/cjh1459463496/article/details/83473100