【AtCoder】ABC 444 B - Digit Sum

B - Digit Sumatcoder.jp favicon

実行時間制限: 2 sec / メモリ制限: 1024 MiB / Difficulty: 36 / NoviSteps: ??? / 配点: 200 点

問題概要

NN 以下の正整数のうち、各桁の和が KK であるものの個数を求めよ。

制約

  • 1N,K1051\leq N,K \leq 10^5
  • 入力は全て整数

考察

x=1,2,,Nx = 1, 2, \cdots, N について、各桁の和を求め、それが KK であれば答えのカウンターを増やしていけばよい。

xx の各桁の和を求める処理は、別に関数化しておくと便利であろう。

実装例

CPP
1.#include <bits/stdc++.h>
2.using namespace std;
3.
4.#define rep(i, start, end) for (auto i = (start); (i) < (end); (i)++)
5.
6.// ======================================== //
7.
8.int main()
9.{
10. int N, K;
11. cin >> N >> K;
12.
13. auto digit_sum = [&](int x) -> int
14. {
15. int res = 0;
16. while (x > 0)
17. {
18. res += x % 10;
19. x /= 10;
20. }
21. return res;
22. };
23.
24. int ans = 0;
25. rep(x, 1, N + 1)
26. {
27. if (digit_sum(x) == K)
28. ans++;
29. }
30.
31. cout << ans << endl;
32.
33. return 0;
34.}
atcoder.jp favicon

実装時間: 5 分以内

コメント

特に言うことはないです。