iT邦幫忙

2021 iThome 鐵人賽

DAY 15
0
自我挑戰組

30天 Leetcode解題之路系列 第 15

Day 15 - Excel Sheet Column Number

大家好,我是毛毛。ヾ(´∀ ˋ)ノ
廢話不多說開始今天的解題Day~


171. Excel Sheet Column Number

Question

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

Example1

Input: columnTitle = "A"
Output: 1

Example2

Input: columnTitle = "AB"
Output: 28

Example3

Input: columnTitle = "ZY"
Output: 701

Example4

Input: columnTitle = "FXSHRXW"
Output: 2147483647

Constraints

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

解題

題目

首先先簡單的翻譯一下題目
給一個columnTitle的String,他代表的是excel中的column,要把他轉換成對應的數字。

Think

作法大致上是這樣

  • ASCII: A:65, Z:90, a:97, z:122
  • "AB"可以拆解成"A"和"B",換算成ascii後"A"變成65、"B"變成66,再統一減去64就可以得到A-Z分別代表的數字。
  • 從個位數開始每個數字的index乘上26的次方,次方為columnTitle的長度-1再減掉for loop跑迴圈時的index,加總起來就得到最後的結果啦。

Code

Python

class Solution:
    def titleToNumber(self, columnTitle: str) -> int:
        # ascii "A"=65, "Z"=90
        # ord() string to ascii
        # chr() ascii to string
        # AZ => A*26^1 + Z*26Z^0
        # AB => A*26 + B*1
        
        column = 0
        for index in range(len(columnTitle)):
            column += (ord(columnTitle[index])-64) * (26**(len(columnTitle)-1-index))
            
        return column

C

int titleToNumber(char * columnTitle){
    long int column = 0;
    long int multiple = 1;
    
    for (int index=strlen(columnTitle)-1 ; index>=0 ; index--){
        column += (( (int)(columnTitle[index])-64 ) * multiple);
        multiple *= 26;
    }
        
    return column;
}

Result

  • Python
  • C

大家明天見/images/emoticon/emoticon29.gif


上一篇
Day 14 - Valid Palindrome
下一篇
Day 16 - Reverse String
系列文
30天 Leetcode解題之路30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言