- Identify the ordered answer range or sorted search domain.
- Write a predicate whose truth changes only once.
- Move the appropriate boundary after each midpoint check and return the final feasible position.
Code notes
- 98 lines of C++ from the credited upstream file sum-of-k-mirror-numbers.cpp.
- The implementation visibly relies on sequence storage.
- 9 loop blocks detected.
Complexity
Multiply the logarithmic number of midpoint checks by the cost of one predicate evaluation.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
123 4class Solution {5public:6 long long kMirror(int k, int n) {7 const int base1 = k, base2 = 10; 8 int64_t result = 0;9 vector<int> prefix_num(2, 1), total(2, base1);10 uint8_t odd = 1;11 while (n--) {12 int64_t x;13 do {14 x = mirror(prefix_num[odd], base1, odd);15 if (++prefix_num[odd] == total[odd]) {16 total[odd] *= base1;17 odd ^= 1;18 }19 } while (x != reverse(x, base2));20 result += x;21 }22 return result;23 }24 25private:26 int64_t mirror(int n, int base, bool odd) {27 int64_t result = n;28 if (odd) {29 n /= base;30 }31 for (; n; n /= base) {32 result = result * base + (n % base);33 }34 return result;35 }36 37 int64_t reverse(int64_t n, int base) {38 int64_t result = 0;39 for (; n; n /= base) {40 result = result * base + n % base;41 }42 return result;43 }44};45 464748class Solution2 {49public:50 long long kMirror(int k, int n) {51 string s = "0";52 int64_t result = 0;53 while (n--) {54 int64_t x;55 do {56 x = next_num_in_base_k(k, &s);57 } while (!is_mirror(to_string(x)));58 result += x;59 }60 return result;61 }62 63private:64 int64_t next_num_in_base_k(int k, string *s) {65 int result = 0;66 for (int i = size(*s) / 2; i < size(*s); ++i) {67 if ((*s)[i] + 1 - k < '0') {68 (*s)[i] = (*s)[size(*s) - 1 - i] = (*s)[i] + 1;69 break;70 }71 (*s)[i] = (*s)[size(*s) - 1 - i] = '0';72 }73 if ((*s)[0] == '0') {74 s->back() = '1';75 s->insert(begin(*s), '1');76 }77 return to_int_from_base_k(*s, k);78 }79 80 int64_t to_int_from_base_k(const string& s, int k) {81 int64_t result = 0;82 for (int64_t i = size(s) - 1, base = 1; i >= 0; --i, base *= k) {83 result += (s[i] - '0') * base;84 }85 return result;86 }87 88 bool is_mirror(const string& s) {89 int left = 0, right = size(s) - 1;90 while (left < right) {91 if (s[left++] != s[right--]) {92 return false;93 }94 }95 return true;96 }97};98