- Translate each rule into one explicit state update.
- Maintain the invariant after every processed item.
- Return the accumulated state once all relevant input has been handled.
Code notes
- 60 lines of C++ from the credited upstream file sum-of-k-digit-numbers-in-a-range.cpp.
- The implementation visibly relies on sequence storage.
- 2 loop blocks detected.
Complexity
Count the number and nesting of passes over the input, then include the maintained containers in the memory estimate.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
123 45class Solution {6public:7 int sumOfNumbers(int l, int r, int k) {8 static const uint32_t MOD = 1e9 + 7;9 10 const auto& addmod = [](uint32_t a, uint32_t b, uint32_t mod) { 11 12 if (mod - a <= b) {13 b -= mod; 14 }15 return a + b;16 };17 18 const auto& submod = [&](uint32_t a, uint32_t b, uint32_t mod) {19 20 return addmod(a, mod - b, mod);21 };22 23 const auto& mulmod = [&](uint32_t a, uint32_t b, uint32_t mod) { 24 25 uint32_t result = 0;26 if (a < b) {27 swap(a, b);28 }29 while (b > 0) { 30 if (b % 2 == 1) {31 result = addmod(result, a, mod);32 }33 a = addmod(a, a, mod);34 b /= 2; 35 } 36 return result; 37 };38 39 const auto& powmod = [&](uint32_t a, uint32_t b, uint32_t mod) {40 a %= mod;41 uint32_t result = 1;42 while (b) {43 if (b & 1) {44 result = mulmod(result, a, mod);45 }46 a = mulmod(a, a, mod);47 b >>= 1;48 }49 return result;50 };51 52 const auto& invmod = [&](uint32_t x, uint32_t mod) {53 return powmod(x, mod - 2, mod);54 };55 56 return mulmod(mulmod((r + l) * (r - l + 1) / 2, powmod(r - l + 1, k - 1, MOD), MOD),57 mulmod(submod(powmod(10, k, MOD), 1, MOD), invmod(10 - 1, MOD), MOD), MOD);58 }59};60