0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

LeetCode / Excel Sheet Column Number

Posted at

[https://leetcode.com/problems/excel-sheet-column-number/]

Given a 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
...

先日の記事はFrom列インデックスTo列名でしたが、今回はFrom列名To列インデックスの変換がお題です。
From列インデックスTo列名の問題が解ければ、こちらも易しいです。

解答・解説

解法1

英字に相当する値を、26のn乗(nは1の位であれば0, 10の位であれば1, 100の位であれば2,,,)に掛け、合計を取ればOKです。

from string import ascii_uppercase

class Solution(object):
    def titleToNumber(self, s):
        """
        :type s: str
        :rtype: int
        """
        d = {}
        for i,e in enumerate(ascii_uppercase):
            d[e] = i+1
        ans = 0
        for i,e in enumerate(s[::-1]):
            ans += d[e] * pow(26,i)
        return ans

こちらの解法が先に思いついてしまいましたが、文字列数分のループを2度回してしまっているところが改善すべき点です。

解法2

アスキーコードを取得するord関数を使えば、ord(char) - 64 に対して26のn乗を掛けるだけで済むので、1度のループで済みます。

class Solution(object):
    def titleToNumber(self, s):
        """
        :type s: str
        :rtype: int
        """
        return sum((ord(char) - 64) * (26 ** exp) for exp, char in enumerate(s[::-1]))
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?