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

提交结果:

相关推荐
·薯条大王3 小时前
经济实惠玩云服务器|一台云服务器多人共用,子账号配置教程
java·linux·运维·服务器·汇编·c++·python
To_OC4 小时前
LC 438 找到所有字母异位词:暴力超时后,我靠滑动窗口一招搞定
javascript·算法·leetcode
白狐_7984 小时前
408数据结构第5章:二叉树遍历序列题——技巧、判断与真题型总结
数据结构
Forever Nore7 小时前
学完C语言力扣第一题做不来正常吗
数据结构·算法
hansang_IR7 小时前
【题解】LC:倍增 / 区间并查集(Range Parallel Unionfind)
c++·算法·并查集
东东最爱敲键盘7 小时前
day7.c++继承
c++
沫璃染墨8 小时前
《从零入门Linux系统篇(十五):系统工具篇·六——GDB调试器详解:从程序执行控制到高级调试技巧》
linux·运维·服务器·c语言·c++
吃着火锅x唱着歌8 小时前
Effective C++ 学习笔记 条款40 明智而审慎地使用多重继承
c++·笔记·学习
Tisfy9 小时前
LeetCode 3731.找出缺失的元素:哈希 / 排序
算法·leetcode·哈希算法·排序·哈希表