[保研/考研机试] 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;
}

提交结果:

相关推荐
努力学习的小廉37 分钟前
我爱学算法之—— 模拟(下)
c++·算法
Larry_Yanan1 小时前
QML学习笔记(十七)QML的属性变更信号
javascript·c++·笔记·qt·学习·ui
海琴烟Sunshine2 小时前
Leetcode 26. 删除有序数组中的重复项
java·算法·leetcode
PAK向日葵2 小时前
【算法导论】NMWQ 0913笔试题
算法·面试
PAK向日葵2 小时前
【算法导论】DJ 0830笔试题题解
算法·面试
PAK向日葵2 小时前
【算法导论】LXHY 0830 笔试题题解
算法·面试
hsjkdhs2 小时前
C++之拷贝构造(浅拷贝与深拷贝)、this指针、内联函数
c++
默|笙2 小时前
【c++】红黑树的部分实现
开发语言·c++
轩情吖2 小时前
Qt常用控件之QSpinBox
开发语言·c++·qt·控件·桌面级开发·qspinbox·微调框
麦麦麦造3 小时前
DeepSeek突然发布 V3.2-exp,长文本能力加强,价格进一步下探
算法