题目描述

给定一个长度不超过 250 的数字串,把这个数字的数位顺序整体颠倒后输出,且结果的开头不能为 0(结果为 0 时输出 0)。

思路

把字符串反转后输出即可:反转后开头的 0 恰好对应原串末尾的 0,删去这些前导 0(其余位置的 0 不动);全 0 输入删成空串时输出 0。数字串长达 250 位,装不进 64 位整数,但这题的"倒序"只是换位置,不产生进位借位,纯字符串操作就能完成。

参考代码

Python 版:

python
#!/usr/bin/env python3
# Author by Rainboy blog: https://rainboylv.com github: https://github.com/rainboylvx
# rbook: -> https://rbook.roj.ac.cn  https://rbook2.roj.ac.cn
# rainboy的学习导航网站: https://idx.roj.ac.cn
# create_at: 2026-10-02 19:17
# update_at: 2026-10-02 19:17

import sys


def solve() -> None:
    """读入数字串,倒序输出并保证结果不以 0 开头。"""
    data = iter(sys.stdin.buffer.read().split())  # 输入只有一个 token,顺序消费即可
    digits = next(data).decode()                  # 题面唯一的输入:一行数字,长度可达 250+

    # 倒序后原串尾部的 0 变成前导 0,lstrip('0') 一次删干净;
    # 整串全 0 时会删成空串,用 or '0' 兜底(如 "0" -> "0")。
    reversed_number = digits[::-1].lstrip('0') or '0'
    print(reversed_number)


if __name__ == "__main__":
    solve()

C++ 版(同一算法):

cpp
/**
 * Author by Rainboy blog: https://rainboylv.com github: https://github.com/rainboylvx
 * rbook: -> https://rbook.roj.ac.cn  https://rbook2.roj.ac.cn
 * rainboy的学习导航网站: https://idx.roj.ac.cn
 * create_at: 2026-10-06 02:11
 * update_at: 2026-10-06 02:11
 */
#include <iostream>
#include <string>
#include <algorithm>
typedef long long ll;
using namespace std;

string s; // 输入的数字串,最长 250 位,装不进整数,按字符串处理

int main() {
    std::ios::sync_with_stdio(false);
    std::cin.tie(nullptr);

    cin >> s;
    // 先把整个串反转:数位倒序不产生进位借位,只需换位置
    reverse(s.begin(), s.end());
    // 反转后开头的 0 就是原串末尾的 0,全部删掉;中间和末尾的 0 保留
    ll pos = 0;
    while (pos + 1 < (ll)s.size() && s[pos] == '0') pos++; // 至少留一位,全 0 时输出 0
    cout << s.substr(pos) << "\n";
    return 0;
}