Official

B - Digit Sum Editorial by en_translator


Original proposer: kyopro_friends

The problem can be solved by computing the digit sum for each integer from \(1\) through \(N\). The implementation becomes clear by separating the computation of digit sum as a function.

To compute the digit sum, one intuitive way is to convert it to a string and inspect each character. Alternatively, we may inspect the ones place while repeatedly dividing by \(10\).

Sample code (C++)

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

int digitsum(int x){
  string s=to_string(x);
  int ans=0;
  for(char c:s)ans+=c-'0';
  return ans;
}

int main(){
  int n,k;
  cin >> n >> k;

  int ans=0;
  for(int i=1;i<=n;i++)if(digitsum(i)==k)ans++;

  cout << ans << endl;
}

Sample code (Python)

def digitsum(x):
  s=str(x)
  ans=0
  for c in s:
    ans+=int(c)
  return ans

n,k=map(int,input().split())
ans=0
for i in range(1,n+1):
  if digitsum(i)==k:
    ans+=1

print(ans)

posted:
last update: