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

提交结果:

相关推荐
pystraf19 分钟前
UOJ 228 基础数据结构练习题 Solution
数据结构·c++·算法·线段树
牙痛不能吃糖,哭25 分钟前
C++面试复习日记(8)2025.4.25,malloc,free和new,delete的区别
开发语言·c++
海底火旺28 分钟前
破解二维矩阵搜索难题:从暴力到最优的算法之旅
javascript·算法·面试
祁同伟.38 分钟前
【数据结构 · 初阶】- 堆的实现
c语言·数据结构
ChoSeitaku1 小时前
17.QT-Qt窗口-工具栏|状态栏|浮动窗口|设置停靠位置|设置浮动属性|设置移动属性|拉伸系数|添加控件(C++)
c++·qt·命令模式
黄昏ivi1 小时前
电力系统最小惯性常数解析
算法
独家回忆3642 小时前
每日算法-250425
算法
烁3472 小时前
每日一题(小白)模拟娱乐篇33
java·开发语言·算法
Demons_kirit2 小时前
LeetCode 2799、2840题解
算法·leetcode·职场和发展
软行2 小时前
LeetCode 每日一题 2845. 统计趣味子数组的数目
数据结构·c++·算法·leetcode