본문 바로가기

Programming/BOJ

[C/C++] BOJ #1081 - Digit Sum

When a number is given, you can find the sum of all its digits. For example, for 47, the sum is \(4+7=11\).  This problem asks you to find the sum of the digits of all numbers within a given range.

 

digit sum



This problem is similar to problem #1019. The only difference is that while #1019 asks for the sum of digits from 1 up to a given number, this problem provides a starting number for the range. Also, #1019 requires outputting the frequency of each digit, whereas this problem asks for the total sum of the digits. Ironically, problem #1019 is rated Gold I in difficulty, while this one is two tiers lower at Gold III.

 

https://odev.tistory.com/entry/CC-BOJ-1019-Book-Page

 

[C/C++] BOJ #1019 - Book Page

Han Ji-min loves books and works at a library.  One spring night, while reading a book, she suddenly became curious about how many digits were written on the pages of the book she was flipping through.  The book’s pages are numbered from page 1 to page

odev.tistory.com


digit sum

 

The source code is largely the same as the one for problem #1019. Please view it for reference purposes.

//----------------------------------------------------------
//    baekjoon #1081 - Digit Sum
//        - by Aubrey Choi
//        - created at 2019-12-31
//----------------------------------------------------------
#include <stdio.h>

//    from #1019
long long sum(long long n)
{
    if(n<=0) return 0;
    long long c[10]={0,}, s=1, sum=0, t, r;
    while(n>0)
    {
        t = n / (s * 10);
        r = n % (s * 10);
        for(int i = 0; i < 10; i++) c[i] += t*s;
        for(int i = 1; i <= r / s; i++) c[i] += s;
        c[(r/s+1)%10] += r % s;
        n -= 9 * s;
        s *= 10;
    }
    for(int i = 1; i < 10; i++) sum+=i*c[i];
    return sum;
}
int main()
{
    long long a, b;
    scanf("%lld%lld", &a, &b);
    printf("%lld\n",sum(b)-sum(a-1));
}
반응형

'Programming > BOJ' 카테고리의 다른 글

[C/C++] BOJ #1074 - Z  (0) 2025.06.29
[C/C++] BOJ #1068 - Tree  (0) 2025.05.19
[C++] BOJ #1067 - Moving  (2) 2025.05.14
[C/C++] BOJ #1057 - Tournament  (1) 2025.05.09
[C/C++] BOJ #1051 - Number Square  (2) 2025.05.05