Four-digit numbers#11652

Four-digit numbers (Editorial)

Solution

General Idea : We are asked to count four-digit numbers whose sum of digits equals a given integer . A four-digit number ranges from to , so we can iterate over all possibilities, compute the sum of digits for each number, and count the matches. Since there are only numbers, this brute-force approach is efficient.


#include <bits/stdc++.h>
using namespace std;
#define int long long

void solve() {
    int n;
    cin >> n;
    int cnt = 0;

    for (int i = 1000; i <= 9999; i++) {
        string s = to_string(i);
        int sum = 0;
        for (char c : s)
            sum += c - '0';
        if (sum == n)
            cnt++;
    }

    cout << cnt;
}

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

    solve();
    return 0;
}