1 条题解

  • -2
    @ 2020-07-13 10:30:04
    #include <iostream>
    #include <algorithm>
    #include <list>
    #include <vector>
    #include <string>
    #include <unordered_map>
    #include <unordered_set>
    
    using namespace std;
    
    class Solution{
    public:
        static unordered_map<char, int> char2int;
        static string int2char;
        // 任意进制加法
        string add(const string& a, const string& b, int base)
        {
            // 表示进位和保存一位数字运算结果
            int carry = 0;
            // 利用链表保存结果,方便从头部插入
            list<char> c;
            // 反向迭代器访问容器
            auto pa = a.rbegin();
            auto pb = b.rbegin();
            while (pa != a.rend() || pb != b.rend())
            {
                // 如果某个迭代器到达结束,则不参与运算
                if (pa != a.rend())
                {
                    carry += char2int[*pa];
                    pa++;
                }
                if (pb != b.rend())
                {
                    carry += char2int[*pb];
                    pb++;
                }
                // 任意进制加法
                c.insert(c.begin(), int2char[carry % base]) ;
                carry /= base ;
            }
            if(carry != 0){
                c.insert(c.begin(), int2char[carry]) ;
            }
            return string(c.begin(), c.end()) ;
        }
        // 判断是否是回文数
        bool isPalindromic(const string& s){
            int r = 0;
            int l = s.length()-1;
            while(r <= l){
                if(s[r] != s[l]){
                    return false;
                }
                r++;
                l--;
            }
            return true;
        }
        void solution(){
            int base = 10;
            string num ;
            int step = 0 ;
            cin >> base;
            cin >> num;
            while(step <= 30){
                // cout << num << endl;
                if(isPalindromic(num)){
                    cout << "STEP=" << step << endl;
                    return;
                }
                // 字符串倒序向加
                string temp(num);
                reverse(temp.begin(), temp.end());
                num = add(num, temp, base);
                step++;
            }
            cout << "Impossible!" << endl;
        }
    };
    
    string Solution::int2char = "0123456789ABCDEF";
    unordered_map<char, int> Solution::char2int = {
        {'0', 0},
        {'1', 1},
        {'2', 2},
        {'3', 3},
        {'4', 4},
        {'5', 5},
        {'6', 6},
        {'7', 7},
        {'8', 8},
        {'9', 9},
        {'A', 10},
        {'B', 11},
        {'C', 12},
        {'D', 13},
        {'E', 14},
        {'F', 15},
    };
    
    int main(int argc, char const *argv[])
    {
        Solution so ;
        so.solution() ;
    }
    
  • 1

信息

ID
1159
难度
7
分类
模拟 点击显示
标签
递交数
183
已通过
42
通过率
23%
上传者