- 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
- 61 lines of C++ from the credited upstream file sum-of-compatible-numbers-in-range-i.cpp.
- The implementation keeps its working state in language-native values and containers.
- 3 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 sumOfGoodIntegers(int n, int k) {8 const auto& count = [&](int x) {9 if (x <= 0) {10 return 0;11 }12 const auto& l = bit_width(static_cast<uint32_t>(x));13 int total = 0, cnt = 1;14 for (int i = 0; i < l; ++i) {15 if (n & (1 << i)) {16 continue;17 }18 total = total * 2 + (1 << i) * cnt;19 cnt *= 2;20 }21 int result = 0, prefix = 0;22 for (int i = l - 1; i >= 0; --i) {23 if ((n & (1 << i)) == 0) {24 if (!(n & (1 << i))) {25 cnt /= 2;26 total = (total - (1 << i) * cnt) / 2;27 }28 }29 if (!(x & (1 << i))) {30 continue;31 }32 result += prefix * cnt + total;33 if (n & (1 << i)) {34 return result;35 }36 prefix |= 1 << i;37 }38 result += prefix;39 return result;40 };41 42 return count(n + k) - count((n - k) - 1);43 }44};45 46474849class Solution2 {50public:51 int sumOfGoodIntegers(int n, int k) {52 int result = 0;53 for (int i = max(n - k, 1); i <= n + k; ++i) {54 if ((n & i) == 0) {55 result += i;56 }57 }58 return result;59 }60};61