1. 程式人生 > >19 . P1553 數字反轉(升級版)

19 . P1553 數字反轉(升級版)

題解:這是洛谷的第19道題目,這個題目的Testcase有很多都想不到,可謂千奇百怪。

注意

1 . 整數的最高位不能為0;

2 . 反轉後的小數的整數部分的最高位不能為0,小數部分的末尾不能為0,除非小數部分都是0,則保留一個0;

3 . 反轉後的分數的分子和分母不用約分,同樣,分子和分母各自的最高位都不為0;

4 . 小數的輸入存在這種測試用例:1020.0101000  ,輸出為:201.101

5 . 反轉後的百分數的整數部分的最高位不為0;

6 . 0反轉後為0;

7 . 需要在輸入字串的時候,需要將‘.’、‘/’、‘%’提取出來,小數需要將整數部分和小數部分都分別提取出來,分數需要將分子和分母分別提取;

原始碼:

#include <iostream>
#include <string.h>
#include <sstream>
#include <stdlib.h>

using namespace std;

void Filp1(const std::string str,int size)
{
    string str1;
    bool zeroornot = true;

    for (size_t i = 0; i < size; i++)
    {
        if (str[i] != '0')
            zeroornot = false;
    }

    if (zeroornot)
        cout << "0";
    else
    {
        bool judge = true;
        for (int i = size - 1; i >= 0; i--)
            str1 += str[i];
        for (size_t i = 0; i < size; i++)
        {
            while (str1[i] == '0' && judge)
                i++;
                
            cout << str1[i];
            judge = false;
        }
    }
}

void Filp2(const std::string str, int size)
{
    string str1 = "";
    bool zeroornot = true;

    for (size_t i = 0; i < size; i++)
    {
        if (str[i] != '0')
            zeroornot = false;
    }
    
    if (zeroornot)
        cout << "0";
    else
    {
        bool judge = true;
        for (size_t i = 0; i < size; i++)
        {
            while (str[i] == '0' && judge)
                i++;

            str1 += str[i];
            judge = false;
        }

        for (int i = str1.size()-1; i >= 0; i--)
            cout << str1[i];
    }
}

int main()
{
    string input;
    string first, second;
    cin >> input;

    string c;
    int inputsize = input.size();
    for (int i = 0; i < inputsize; i++)
    {
        if (input[i] == '0' || input[i] == '1' || input[i] == '2' || input[i] == '3' || input[i] == '4' ||
            input[i] == '5' || input[i] == '6' || input[i] == '7' || input[i] == '8' || input[i] == '9')
            second += input[i];
        else
        {
            c = input[i];
            first = second;
            second = "";
        }
    }

    if (c == ".")
    {
        Filp1(first, first.size());
        cout << c;
        Filp2(second, second.size());
    }
    else if (c == "/")
    {
        Filp1(first, first.size());
        cout << c;
        Filp1(second, second.size());
    }
    else if (c == "%")
    {
        Filp1(first, first.size());
        cout << c;
    }
    else
        Filp1(second, second.size());
        
    cout << endl;
    system("pause");
    return 0;
}