C++ Problem P1553: Number Reversal (Upgraded Version)

Click the blue text

Follow us

C++ Problem P1553: Number Reversal (Upgraded Version)

P1553 Number Reversal (Upgraded Version)

Problem Background

The following is the original problem statement for reference:

Given a number, please reverse the digits of the number to obtain a new number.

This time, unlike the first question of the NOIp2011 popular group, this number can be a decimal, fraction, percentage, or integer. The integer reversal means swapping all digits; the decimal reversal means reversing the integer part and the decimal part separately without swapping them; the fraction reversal means reversing the denominator and the numerator separately without swapping them; the percentage’s numerator must be an integer, and the percentage only changes the numeric part. The new integer must also meet the common form of integers, that is, unless the original number given is zero, the highest digit of the new number obtained after reversal should not be zero; the new decimal number should not end with zero (unless the decimal part has no other digits besides zero, in which case only one zero should be kept); fractions should not be simplified, and both the numerator and denominator are not decimals (sorry for those who simplify fractions, it cannot be accepted. The input data guarantees that the denominator is not zero), and there are no negative numbers this time.

Problem Description

Given a number, please reverse the digits of the number to obtain a new number.

This time, unlike the first question of the NOIp2011 popular group, this number can be a decimal, fraction, percentage, or integer.

  • Integer reversal means swapping all digits.

  • Decimal reversal means reversing the integer part and the decimal part separately without swapping them.

  • Fraction reversal means reversing the denominator and the numerator separately without swapping them.

  • The numerator of a percentage must be an integer, and the percentage only changes the numeric part.

Input Format

  • A real number

Output Format

  • A real number, which is the reversed number of .

Input Examples

#1

5087462

#2

600.084

#3

700/27

#4

8670%

Output Examples

#1

2647805

#2

6.48

#3

7/72

#4

768%

Notes/Tips

【Data Range】

  • For , the data is an integer, not exceeding digits;

  • For , the data is a decimal, with both the integer and decimal parts not exceeding digits;

  • For , the data is a fraction, with both the numerator and denominator not exceeding digits;

  • For , the data is a percentage, with the numerator not exceeding digits.

【Data Guarantee】

  • For integer reversal, both the original integer and the new integer must meet the common form of integers, that is, unless the original number given is zero, the highest digit of the new number obtained after reversal should not be zero.

  • For decimal reversal, the part before the decimal point must meet the common form of integers, and the part after the decimal point must also meet the common form of decimals, which means no trailing zeros (if the decimal part has no other digits besides zero, only one zero should be kept. If trailing zeros appear after reversal, please omit the excess zeros).

  • For fraction reversal, fractions should not be simplified, and both the numerator and denominator are not decimals. The input denominator is not zero. The related regulations for integer reversal apply.

  • For percentage reversal, refer to the related content for integer reversal.

There are no negative numbers in the data.

💡 Problem Analysis

This problem requires reversing the input number string, supporting integers, decimals, fractions, and percentages with different reversal rules, while adhering to specific format specifications (such as removing leading zeros for integers and trailing zeros for decimals). The core challenge lies in accurately identifying the input type, splitting the components, and processing them according to the rules, ultimately concatenating them into a valid result.

💡 Solution Approach

  1. Type Judgment: Distinguish between percentages, fractions, decimals, and integers based on whether the input string contains %, /, or ..

  2. Splitting and Processing:

    1. Percentage: Extract the numeric part before %, reverse it according to integer rules, and add %.

    2. Fraction: Split by / into numerator and denominator, reverse them according to integer rules, and concatenate.

    3. Decimal: Split by . into integer and decimal parts, reverse the integer part according to integer rules; reverse the decimal part and remove trailing zeros.

    4. Integer: Directly reverse and remove leading zeros.

  3. Rule Adaptation: Implement two core processing functions:

    1. process_integer: Reverse the integer string and remove leading zeros.

    2. process_decimal: Reverse the decimal string and remove trailing zeros.

📐Mathematical Principles

This problem essentially involves string reversal and normalization, without complex mathematical operations, focusing on the reverse arrangement of digit positions and format correction:

  • Integer Reversal: Completely reverse the order of digits (e.g., 5087462 → 2647805).

  • Leading Zero Handling: If the first digit is 0 and the length is greater than 1 after reversal, remove leading zeros (e.g., 600 reversed becomes 006 → 6).

  • Trailing Zero Handling: After reversing the decimal part, if there are trailing zeros and there are non-zero digits, remove trailing zeros (e.g., 084 reversed becomes 480 → 48).

🧰 Programming Principles

  • String Operations: Use substr to split strings and reverse to reverse character order.

  • Conditional Judgments: Use the find function to detect special characters (%, /, .) to distinguish types.

  • Boundary Handling: Special handling for all-zero strings (e.g., 000) to ensure valid output format (e.g., keep one 0).

🧾Code Implementation

#include<iostream>#include<algorithm> // For reverse function#include<string>using namespace std;// Process integer type number string: reverse and remove leading zerosstring process_integer(string s){    reverse(s.begin(), s.end()); // Reverse string    // Check if all are zeros    bool all_zero = true;    for (char c : s) {        if (c != '0') {            all_zero = false;            break;        }    }    if (all_zero) return "0"; // All zeros return "0"    // Remove leading zeros: find the first non-zero character    size_t start = 0;    while (start < s.size() && s[start] == '0') {        start++;    }    return s.substr(start); // Return substring starting from the first non-zero character}// Process decimal type number string: reverse and remove trailing zerosstring process_decimal(string s){    reverse(s.begin(), s.end()); // Reverse string    // Check if all are zeros    bool all_zero = true;    for (char c : s) {        if (c != '0') {            all_zero = false;            break;        }    }    if (all_zero) return "0"; // All zeros return "0"    // Remove trailing zeros: find the last non-zero character    size_t end = s.size() - 1;    while (end >= 0 && s[end] == '0') {        end--;    }    return s.substr(0, end + 1); // Return substring ending at the last non-zero character}int main(){    string s;    cin >> s;    string res;    if (s.find('%') != string::npos) { // Percentage handling        string num = s.substr(0, s.size() - 1); // Extract numeric part        res = process_integer(num) + "%";    } else if (s.find('/') != string::npos) { // Fraction handling        size_t pos = s.find('/');        string numerator = s.substr(0, pos); // Numerator        string denominator = s.substr(pos + 1); // Denominator        res = process_integer(numerator) + "/" + process_integer(denominator);    } else if (s.find('.') != string::npos) { // Decimal handling        size_t pos = s.find('.');        string int_part = s.substr(0, pos); // Integer part        string dec_part = s.substr(pos + 1); // Decimal part        res = process_integer(int_part) + "." + process_decimal(dec_part);    } else { // Integer handling        res = process_integer(s);    }    cout << res << endl;    return 0;}

Click below to read the original text

Direct access to the Luogu problem bank for practice

🛠️ Programming Tips

  • Type Priority Judgment: Determine type in the order of % → / → ., to avoid ambiguity (e.g., % can only appear at the end).

  • Function Reuse: Encapsulate the reversal logic for integers and decimals into independent functions to improve code reusability.

  • All-Zero Handling: Through

📚 Function / Method Usage Instructions

C++ Problem P1553: Number Reversal (Upgraded Version)

📚 Variable and Function Vocabulary Cards

  • reverse: Reverse a string (e.g., abc → cba).

  • substr(pos, len): Extract a substring (pos starting position, len length, default to the end).

  • find(char): Find character position, returns string::npos if not found.

  • process_integer: process (handle) + integer (integer) → handle integer type string.

  • process_decimal: process (handle) + decimal (decimal) → handle decimal type string.

⏱️ Time & Space Complexity Analysis

  • Time Complexity: O(n), where n is the length of the input string. Reversing the string, traversing to check for all zeros, finding delimiters, etc., are all linear time operations.

  • Space Complexity: O(n), mainly used to store the split substrings (e.g., numerator, denominator, integer part, etc.), length not exceeding the original string.

🧩 Problem Summary

The core of this problem is the detailed processing of strings, requiring the splitting and reversing of components according to the rules for different number types (integers, decimals, fractions, percentages), while strictly adhering to format specifications (such as removing leading zeros and trailing zeros). By encapsulating processing functions and prioritizing type judgments, efficient logic reuse and accurate classification can be achieved, ensuring correct output for boundary cases (e.g., all-zero input).

Code Running Examples:

  • Input 600.084 → Output 6.48

  • Input 700/27 → Output 7/72

  • Input 8670% → Output 768%

END

C++ Problem P1553: Number Reversal (Upgraded Version)C++ Problem P1553: Number Reversal (Upgraded Version)

Like

Collect

Share

C++ Problem P1553: Number Reversal (Upgraded Version)

Explore the forefront of educational technology and empower future learning!

“Bit Island Education Technology” is committed to using innovative technology to create a more efficient, interesting, and future-oriented learning experience.

  • Get the latest educational technology products and course materials

  • Learn practical and efficient learning methods and educational concepts

  • Discover innovative teaching tools and classroom application cases

  • Participate in exclusive events and win learning benefits

Scan the code to follow us and start your journey in smart education! 👇

BIT ISLAND

C++ Problem P1553: Number Reversal (Upgraded Version)

Long press to scan

WeChat IDbit_island_Terry

WeChat SearchBit Island Education Technology

C++ Problem P1553: Number Reversal (Upgraded Version)

Leave a Comment