정화 코딩

[C++] 1 빼기 (백준 25709번) 본문

PS

[C++] 1 빼기 (백준 25709번)

jungh150c 2025. 4. 2. 15:31

https://www.acmicpc.net/problem/25709

 

#include <iostream>
using namespace std;

int main() {
    ios_base::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);

    int n;
    cin >> n;

    int ans = 0;

    string s = to_string(n);
    string tmps = "";

    for (char c: s) {
        if (c == '1') ans++;
        else tmps += c;
    }

    if (tmps.empty()) n = 0;
    else n = stoi(tmps);

    while (n > 0) {
        int tmp = n % 10;

        if (tmp == 0) {
            n -= 9;
            ans += 9;
        } else if (tmp == 1) {
            ans++;
            n /= 10;
        } else {
            n -= (tmp - 1);
            ans += (tmp - 1);
        }
    }

    cout << ans << '\n';
}

일단 처음부터 한 자리씩 쭉 보면서 1이면 제거한다. 그러고 난 후 뒤에서부터 보면서 1씩 빼고 1이 되면 제거한다. (AC)

 

    n = stoi(tmps);

참고로 처음에는 이렇게만 해주었더니 런타임 에러(invalid_argument)가 났다. tmps가 빈 문자열일 수도 있는데, 그런 경우에 int로 바꾸는 과정에서 오류가 발생하기 때문이다. 

    if (tmps.empty()) n = 0;
    else n = stoi(tmps);

따라서 위와 같이 빈 문자열인지 체크를 해준 뒤에 int로 변환해주어야 한다. 

 

Comments