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

Posted 二十六画生的博客

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode 171. Excel Sheet Column Number-Excel的列名转换为具体的数字AB->28,ZY->701相关的知识,希望对你有一定的参考价值。

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"].
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"));
    

以上是关于Leetcode 171. Excel Sheet Column Number-Excel的列名转换为具体的数字AB->28,ZY->701的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode 171. Excel Sheet Column Number

LeetCode 171. Excel Sheet Column Number

LeetCode 171. Excel Sheet Column Number

LeetCode之171. Excel Sheet Column Number

LeetCode: 171 Excel Sheet Column Number(easy)

LeetCode 171 Excel Sheet Column Number