Leetcode 171. Excel Sheet Column Number-Excel的列名转换为具体的数字AB->28,ZY->701

74 阅读1分钟

一起养成写作习惯!这是我参与「掘金日新计划 · 4 月更文挑战」的第4天,点击查看活动详情

Given a string columnTitle that represents the column title as appear in an Excel sheet, return

its corresponding column number

.

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

Constraints:

  • 1 <= columnTitle.length <= 7
  • columnTitle consists only of uppercase English letters.
  • columnTitle is in the range ["A", "FXSHRXW"].

Excel的列名转换为具体的数字AB->28,ZY->701

package com.string;
 
/**
 * @Author you guess
 * @Date 2022/4/8 11:09
 * @Version 1.0
 * @Desc Excel的列名转换为具体的数字AB->28,ZY->701
 * Example 2:
 * Input: columnTitle = "AB"
 * Output: 28
 * <p>
 * Example 3:
 * Input: columnTitle = "ZY"
 * Output: 701
 */
public class Leetcode_171_ExcelSheetColumnNumber {
 
    /**
     * 方法1:从后往前遍历
     * Runtime: 3 ms, faster than 22.02% of Java online submissions for Excel Sheet Column Number.
     * Memory Usage: 42.8 MB, less than 45.26% of Java online submissions for Excel Sheet Column Number.
     *
     * @param columnTitle
     * @return
     */
    public int titleToNumber1(String columnTitle) {
        //char[] carr = columnTitle.toCharArray();//没必要转换
        int sum = 0;
        //从后往前遍历
        for (int i = columnTitle.length() - 1; i >= 0; i--) {
            sum += (columnTitle.charAt(i) - 'A' + 1) * Math.pow(26, columnTitle.length() - 1 - i);
        }
        return sum;
    }
 
 
    /**
     * 方法2:从前往后遍历
     * Runtime: 2 ms, faster than 73.30% of Java online submissions for Excel Sheet Column Number.
     * Memory Usage: 43.1 MB, less than 21.51% of Java online submissions for Excel Sheet Column Number.
     *
     * @param columnTitle
     * @return
     */
    public int titleToNumber(String columnTitle) {
        //char[] carr = columnTitle.toCharArray();//没必要转换
        int sum = 0;
        //从前往后遍历
        for (int i = 0; i < columnTitle.length(); i++) {
            sum *= 26;//不用pow(z,y)
            sum += (columnTitle.charAt(i) - 'A' + 1);
        }
        return sum;
    }
 
    public static void main(String[] args) {
        Leetcode_171_ExcelSheetColumnNumber main = new Leetcode_171_ExcelSheetColumnNumber();
        //System.out.println(main.titleToNumber("AB"));//28
        System.out.println(main.titleToNumber("ZY"));
    }
}

end