---
title: "二的幂次方-题解"
description: "任何一个正整数都可以用 2 的幂次方表示。"
canonical_url: "https://yangqiuyi.com/blog/suan-fa/er-de-mi-ci-fang-ti-jie"
---

> Index of every page on this site: [llms.txt](https://yangqiuyi.com/llms.txt)

# 题目描述

任何一个正整数都可以用 2 的幂次方表示。

例如：

```text
137 = 2^7 + 2^3 + 2^0
```

同时约定次方用括号来表示，即 ab 可表示为 a（b）。

由此可知，137 可表示为：

```text
2（7）+2（3）+2（0）
```

进一步：7 = 2^2 + 2 + 2^0（21 用 2 表示）

```text
3=2+2^0
```

所以最后 137 可表示为：

```text
2（2（2）+2+2（0））+2（2+2（0））+2（0）
```

又如：

```text
1315=2^10 +2^8 +2^5 +2+1
```

所以 1315 最后可表示为：

```text
2（2（2+2（0））+2）+2（2（2+2（0）））+2（2（2）+2（0））+2+2（0）
```

## 输入

每个测试文件只包含一组测试数据，每组输入一个正整数 n（n<=20000）。

## 输出

对于每组输入数据，输出符合约定的 n 的 0，2 表示。（在表示中不能有空格）

## 样例输入

```text
137
```

## 样例输出

```text
2(2(2)+2+2(0))+2(2+2(0))+2(0)
```

## 思路

一看就要递归，然后拿张纸自己算了算，大概知道了拆解过程，便计算边输出，不需要返回值，因此定义一个void d(int n)
d函数得到一个整数n，先判断是否需要继续拆解。

```text
pow(x,y)是C语言函数，返回x^y,类型为double
```

## 我的代码

```cpp
#include <bits/stdc++.h>

using namespace std;

void d(int n){
    if(n==1){
        cout<<"2(0)";
    }else if(n==2){
        cout<<"2";
    }else{
        int i,s=0;
        for(i=1;n-pow(2,i)>0;i++);
        int res=n-pow(2,i);
        if(res<0){
            i--;
            res=n-pow(2,i);
        }
        if(i>1){
            cout<<"2(";
            d(i);
            cout<<")";
        }else{
                cout<<"2";
        }
        if(res!=0){
            cout<<"+";
            d(res);
        }
    }
    return;
}

int main(){
    int n;
    cin>>n;
    d(n);
    return 0;
}
```

## Sitemap

See the full [sitemap](https://yangqiuyi.com/sitemap.md) for all pages.
