Ritual Algorithm Mathematics—Excel Column Number

Table of contents

Excel table column number

answer:

code:


Excel table column number

171. Excel column serial number - LeetCode

You are given a string columnTitle representing the column name in the Excel table. Returns the column ordinal corresponding to the column name.

For example:

A -> 1
B -> 2
C -> 3
...
Z -> 26
AA -> 27
AB -> 28 
...
 

Example 1:

Input: columnTitle = "A"
Output: 1
Example 2:

Input: columnTitle = "AB"
Output: 28
Example 3:

Input: columnTitle = "ZY"
Output: 701

answer:

Refer to the solution of this question, the same is the base conversion, which is the reverse of the idea of ​​this question

(37 messages) Likou Algorithm Mathematics Class—Excel Table Column Name_turbo Summer Soseki's Blog-CSDN Blog

code:

class Solution {
    public int titleToNumber(String columnTitle) {
        //计算字符串长度
        int n=columnTitle.length();
        //记录结果
        int res=0;
        //循环
        for(int i=0;i<n;i++){
            int a= (int)(columnTitle.charAt(i)-'A');//余数
            res=res*26+a+1;//商×26+余数+1
        }
        return res;
    }
}

Guess you like

Origin blog.csdn.net/qq_62799214/article/details/131768827