蓝桥杯算法题解 算法训练 2的次幂表示

题目描述

问题描述
  任何一个正整数都可以用2进制表示,例如:137的2进制表示为10001001。
  将这种2进制表示写成2的次幂的和的形式,令次幂高的排在前面,可得到如下表达式:137=27+23+2^0
  现在约定幂次用括号来表示,即a^b表示为a(b)
  此时,137可表示为:2(7)+2(3)+2(0)
  进一步:7=22+2+20 (2^1用2表示)
  3=2+2^0
  所以最后137可表示为:2(2(2)+2+2(0))+2(2+2(0))+2(0)
  又如:1315=210+28+2^5+2+1
  所以1315最后可表示为:
  2(2(2+2(0))+2)+2(2(2+2(0)))+2(2(2)+2(0))+2+2(0)
输入格式
  正整数(1<=n<=20000)
输出格式
  符合约定的n的0,2表示(在表示中不能有空格)
样例输入
137
样例输出
2(2(2)+2+2(0))+2(2+2(0))+2(0)
样例输入
1315
样例输出
2(2(2+2(0))+2)+2(2(2+2(0)))+2(2(2)+2(0))+2+2(0)
提示
  用递归实现会比较简单,可以一边递归一边输出

题解:

写一个递归函数,实现思路:

  1. 一个数组用于记录整数n的二进制表示中,从低位到高位,出现1的时候对应的位置,比如137(10) = 10001001(2),从低位到高位出现1对应的位置,tmp[0]=0 tmp[1] = 3 tmp[2] = 7,可以看出:,137 = 27 + 23 + 20
  2. 然后从高位往低位枚举,因为输出的顺序是先大幂后小幂,每次遍历到一个tmp[i]就进行判断:
    如果为0,直接输出2(0)
    如果为1,直接输出2
    如果为2,直接输出2(2),
    如果 > 2,也就是3以上的数,就递归函数fun(tmp[i]),比如fun(7),就是继续求7的表示方式。
    每次遍历完一次后,要判断,如果不是最后一个位置,每次要在后面输出一个+号。

代码:

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <climits>
#include <cstring>
#include <string>
#include <algorithm>
#include <vector>
#include <deque>
#include <list>
#include <utility>
#include <set>
#include <map>
#include <stack>
#include <queue>
#include <bitset>
#include <iterator>
using namespace std;

typedef long long ll;
const int inf = 0x3f3f3f3f;
const ll  INF = 0x3f3f3f3f3f3f3f3f;
const double PI = acos(-1.0);
const double E = exp(1.0);
const int MOD = 1e9+7;
const int MAX = 1e5+5;
int n;

void fun(int x)
{
    int tmp[32+5];
    int cnt = 0;
    int pos = 0;// 记录每个1的位置
    while(x)
    {
        int t = x % 2;
        if(t == 1)
        {
            tmp[cnt++] = pos;
        }
        pos++;
        x /= 2;
    }
    for(int i = cnt-1; i >= 0; i--)
    {
        if(tmp[i] == 0)
        {
            cout << "2(0)";
        }
        else if(tmp[i] == 1)
        {
            cout << "2";
        }
        else if(tmp[i] == 2)
        {
            cout << "2(2)";
        }
        else
        {
            cout << "2(";
            fun(tmp[i]);
            cout << ")";
        }
        if(i != 0)
        {
            cout << "+";
        }
    }
}

int main()
{
    /*
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    */

    while(cin >> n)
    {
        fun(n);
        cout << endl;
    }

    return 0;
}


























发布了197 篇原创文章 · 获赞 18 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/qq_41708792/article/details/103092411