zoukankan      html  css  js  c++  java
  • 【面试向】2019 年微软秋招笔试 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

    若 $x = y + r(y)$,其中 $r(y) := ext{reverse of $y$}$,则可以确定 $y$ 是几位数。

    若 $x$ 的最高位上的数字大于 $1$,则 $y$ 与 $x$ 位数相同。
    若 $x$ 的最高位上的数字等于 $1$,则 $x$ 的最高位可能是 $ y + r(y)$ 进位导致的,于是有两种可能

    1. $y$ 与 $x$ 位数相同
    2. $y$ 比 $x$ 少一位

    此时,我们可以分别讨论这两种情况。确定了 $y$ 的位数,进一步可以确定符合条件的 $y$ 是否存在。我们只需要判断,在不进位的情况下,$x$ 是否是回文串,特别的,当 $y$ 的长度是奇数时,中间的那一位上必须是偶数。

    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

  • 相关阅读:
    PHP | 运算符优先级
    Docker配置PHP+Nginx+MySQL
    Windows下Mysql主从配置
    php-fpm重启配置修改无效
    MySQL事务
    hadoop伪集群搭建
    Springboot2.x源码下载安装
    微服务——服务之间访问,用Feign请求服务接口超时如何解决?
    Lua安装
    日期——计算每月第一天和最后一天
  • 原文地址:https://www.cnblogs.com/Patt/p/11570165.html
Copyright © 2011-2022 走看看