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

提交结果:

相关推荐
-一杯为品-42 分钟前
【深度学习】#11 优化算法
人工智能·深度学习·算法
_F_y43 分钟前
list简单模拟实现
c++·list
前进的程序员1 小时前
C++ 在 Windows 和 Linux 平台上的开发差异及常见问题
linux·c++·windows
-qOVOp-1 小时前
zst-2001 上午题-历年真题 计算机网络(16个内容)
网络·计算机网络·算法
Swift社区1 小时前
涂色不踩雷:如何优雅解决 LeetCode 栅栏涂色问题
算法·leetcode·职场和发展
冠位观测者1 小时前
【Leetcode 每日一题】2900. 最长相邻不相等子序列 I
数据结构·算法·leetcode
努力写代码的熊大1 小时前
链表的中间结点数据结构oj题(力扣876)
数据结构·leetcode·链表
真的没有脑袋1 小时前
概率相关问题
算法·面试
y102121041 小时前
Pyhton训练营打卡Day27
java·开发语言·数据结构
daiwoliyunshang1 小时前
哈希表实现(1):
数据结构·c++