ZeroJudge F360: Shady's Replica

There are N slim shadys, but only one is the real slim shady. The rest are imitating. How many are imitating?

Sample Inputs/Outputs

Sample Input(s)Sample Output(s)
The input consists of no more than 100 lines. Each line contains an integer N (2 ≤ N ≤ 10^1000). The input ends with EOF.Output how many are imitating.
2
10
100000
1
9
99999

Thought Process

Use strings to collect data, and declare a function to subtract 1, with a string ans initialized to an empty string.

In the function, two parameters are needed: the current position position and a boolean value minus indicating whether to subtract one. If position == -1, return from the function. If the current position needs to be decremented, check if the character at the current position is '0'. If it is '0', call the function with position - 1 and minus set to true, and append '9' to ans. Otherwise, convert the character to a number, subtract 1, and append the result to ans. If minus is false, append the character at the current position to ans and call the function with position - 1 and false.

In the main function, call the function with the string's length minus one and true.

When outputting, reverse the output of ans, and declare a boolean value first outside the loop to remove leading zeros. If the current character is '0' and first == true, continue; otherwise, set first to false and output the current character.

Sample Code-ZeroJudge F360: Shady's Replica

#include <iostream>
using namespace std;

string ans = "", str;

void minusOne(const bool minus, const int position) {
    if (position == -1) return;
    if (minus) {
        if (str[position] == '0') {
            ans += '9';
            minusOne(true, position-1);
        }
        else {
            const int num = int(str[position] - '0');
            ans += to_string(num-1);
            minusOne(false, position-1);
        }
    }
    else {
        ans += str[position];
        minusOne(false, position-1);
    }
}

int main() {
    cin.sync_with_stdio(0);
    cin.tie(0);
    while (cin >> str) {
        ans = "";
        minusOne(true, str.length()-1);
        bool first = true;
        for (int i = ans.length()-1; i>=0; i--) {
            if (ans[i] == '0') {
                if (first) continue;
            }
            first = false;
            cout << ans[i];
        }
        cout << "\n";
    }
}

//ZeroJudge F360
//Dr. SeanXD

Comments