- 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
- 56 lines of C++ from the credited upstream file count-binary-palindromic-numbers.cpp.
- The implementation visibly relies on sequence storage.
- 4 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 countBinaryPalindromes(long long n) {8 const auto& length = [&](int64_t n) {9 int result = 0;10 for (; n; n >>= 1) {11 ++result;12 }13 return result;14 };15 16 const auto& reverse = [](int64_t n, int l) {17 int64_t result = 0;18 for (int i = 0; i < l; ++i) {19 if (n & (1 << i)) {20 result |= 1 << ((l - 1) - i);21 }22 }23 return result;24 };25 26 const auto& l = length(n) / 2;27 const auto& p = ((n >> l) << l) | reverse(n >> (length(n) - l), l);28 return ((1 << l) - 1) + (n >> l) + (p <= n ? 1 : 0);29 }30};31 32333435class Solution2 {36public:37 int countBinaryPalindromes(long long n) {38 const auto& to_binary = [&](int64_t n) {39 string result;40 for (; n; n >>= 1) {41 result.push_back(n & 1);42 }43 reverse(begin(result), end(result));44 return result;45 };46 47 const auto& s = to_binary(n);48 const int l = size(s) / 2;49 string p = s.substr(0, size(s) - l);50 for (int i = 0; i < l; ++i) {51 p.push_back(s[(l - 1) - i]);52 }53 return ((1 << l) - 1) + (n >> l) + (p <= s ? 1 : 0);54 }55};56