letter base conversion

  Question: In Excel2003, use A for column 1, B for column 2... Z for column 26, AA for column 27, AB for column 28... and so on . Please write a function, input the column number code represented by letters, and output what column it is.

 

//这是一道关于进制的题目,其本质是把十进制数字用A~Z表示成二十六进制。

#include<iostream>
#include<string>
using namespace std;

int StringToInt(const string& str)
{
    int length = str.length();
    if (length < 0)
    {
        cout << "无效输入" << endl;
        return -1;
    }

    int sum = 0; //如果输入的字符为空字符,输出为0。

    for (int i = 0; i < str.length(); i++)
    {
        int value = str[i] - 'A';
        if (value >= 26 || value < 0)
        {
            cout << "无效输入" << endl;
        }

        sum = 26 * sum + value + 1;

    }

    return sum;
}

int main()
{
    string str;
    //while (getline(cin, str))
    cin >> str;
    cout << StringToInt(str) << endl;

    return 0;
}

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325061824&siteId=291194637