[Interview] to move the fall of 2019, Microsoft Written Problem 3

Problem

Check if a positive integer $n$ can be written as sum of a positive integer and reverse of that integer.
Here, reverse of a positive integer is defined as the integer obtained by reversing the decimal representation of that integer.

For example, 121 = 92 + 29.

Analysis

If $ x = y + r (y) $, where $ r (y): = \ text {reverse of $ y $} $, $ Y $ can be determined by several digits.

If the number is on the highest level is greater than $ X $ $ $ 1, the $ Y $ and X $ $ identical digits.
If the number is on the highest level is equal to x $ $ $ $ 1, the most significant bit is $ x $ may be $ y + r (y) $ carry lead, so there are two possible

  1. $ Y $ and $ x $ the same number of digits
  2. $ Y $ less than $ x $ a

At this point, we can discuss these two cases separately. Determining the median $ y $, and further can be determined eligible $ y $ exists. We only need to determine, in not carry case, the $ X $ whether palindromic sequence, in particular, when $ Y $ length is an odd number, an intermediate that must be even.

Implementation

// x = y + reverse(y)
// y 有 d.size() 位
bool check(vector<int> d) {
    for (int i = 0, j = (int)d.size() - 1; i < j; ++i, --j) {
        // case 1: d[i] == d[j]
        // case 2: d[i] == d[j] + 10
        // case 2: d[i] - 1 == d[j]
        // case 3: d[i] - 1 == d[j] + 10
        if (d[i] == d[j]) continue;
        if (d[i] == d[j] + 10) d[j - 1] -= 1;
        else if (d[i] - 1 == d[j]) {
            d[i + 1] += 10;
        }
        else if (d[i] - 1 == d[j] + 10) {
            d[i + 1] += 10;
            d[j - 1] -= 1;
        }
        else {
            return false;
        }
    }
    if (d.size() & 1) {
        int t = d[d.size() / 2];
        return t % 2 == 0 && t >= 0 && t <= 18;
    }
    return true;
}

bool solve(const char* s) {
    vector<int> d;
    for (int i = 0; s[i]; ++i) {
        d.push_back(s[i] - '0');
    }
    bool res = check(d);
    if (d.front() == 1 && d.size() > 1) {
        d[1] += 10;
        d.erase(d.begin());
        res |= check(d);
    }
    return res;
}

Related materials

https://stackoverflow.com/q/54694588

https://www.mathpages.com/home/kmath004/kmath004.htm

Guess you like

Origin www.cnblogs.com/Patt/p/11570165.html