[保研/考研机试] KY103 2的幂次方 上海交通大学复试上机题 C++实现

题目链接:

KY103 2的幂次方 https://www.nowcoder.com/share/jump/437195121691999575955

描述

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.

中文描述:

每个正数都可以用指数形式表示。例如,137 = 2^7 + 2^3 + 2^0。我们用a(b)的形式表示a^b。那么137可以用2(7)表示 +2(3)+2(0)。 由于 7 = 2^2 + 2 + 2^0 和 3 = 2 + 2^0 ,因此 137 最终由 2(2(2)+2 +2(0))+2(2+2(0)) 表示 +2(0)。 给定一个正数 n,你的任务是将 n 以仅包含数字 0 和 2 的指数形式呈现。

输入描述:

对于每种情况,输入文件都包含一个正整数 n (n<=20000)。

输出描述:

对于每种情况,您应该在一行中输出 n 的指数形式。请注意,该行中不应有任何额外的空格。

示例1

输入:

cpp 复制代码
1315

输出:

cpp 复制代码
2(2(2+2(0))+2)+2(2(2+2(0)))+2(2(2)+2(0))+2+2(0)

思路:

  1. 首先,定义一个递归函数 powTwo,将数字 n 转换为二进制形式,其中只有 0 和 1。

  2. 在递归函数中,处理二进制数,如果某一位为 1,则根据指数规则,将其转换为对应的 2(a) 形式。

  3. 注意处理特殊情况,例如 2^1 直接表示为 "+2",其他情况通过递归处理更高次幂。

  4. 最后,去掉字符串开头的 "+" 符号,即为所求的指数形式表示。

  5. 在 main 函数中,读入输入的正整数 n,并调用递归函数 powTwo 输出结果。

源代码:

cpp 复制代码
#include <iostream>
#include <vector>
using namespace std;

// 定义递归函数,将数字 n 转换为指数形式
string powTwo(int n) {
    if (n == 0) {
        return "0";
    }
    if (n == 2) {
        return "2";
    }
    vector<int> nums;
    while (n != 0) {
        nums.push_back(n % 2); // 将 n 转换为二进制
        n /= 2;
    }
    string res = "";
    for (int i = nums.size() - 1; i >= 0; i--) {
        if (nums[i] == 1) {
            if (i == 1) {
                res += "+2"; // 如果是 2^1,直接添加 "+2"
            }
            else {
                res += "+2(" + powTwo(i) + ")"; // 否则递归处理更高次幂
            }
        }
    }
    res.erase(0, 1); // 去掉最前面的 "+"
    return res;
}

int main() {
    int n;
    while (cin >> n) {
        cout << powTwo(n) << endl;
    }

    return 0;
}

提交结果:

相关推荐
金融小师妹9 分钟前
基于哈塞特独立性表态的AI量化研究:美联储政策独立性的多维验证
大数据·人工智能·算法
纪元A梦4 小时前
贪心算法应用:化工反应器调度问题详解
算法·贪心算法
阿让啊4 小时前
C语言strtol 函数使用方法
c语言·数据结构·c++·单片机·嵌入式硬件
深圳市快瞳科技有限公司4 小时前
小场景大市场:猫狗识别算法在宠物智能设备中的应用
算法·计算机视觉·宠物
liulilittle4 小时前
OPENPPP2 —— IP标准校验和算法深度剖析:从原理到SSE2优化实现
网络·c++·网络协议·tcp/ip·算法·ip·通信
superlls7 小时前
(算法 哈希表)【LeetCode 349】两个数组的交集 思路笔记自留
java·数据结构·算法
田里的水稻7 小时前
C++_队列编码实例,从末端添加对象,同时把头部的对象剔除掉,中的队列长度为设置长度NUM_OBJ
java·c++·算法
纪元A梦7 小时前
贪心算法应用:保险理赔调度问题详解
算法·贪心算法
Ripple123128 小时前
数据结构:顺序表与链表
数据结构·链表
Jayden_Ruan8 小时前
C++逆向输出一个字符串(三)
开发语言·c++·算法