algorithm notes: leetcode#171 excel sheet column number

Problem


Solution


Analysis

Python implementation

1
2
3
4
5
6
7
8
9
10
class :
def titleToNumber(self, s):
"""
:type s: str
:rtype: int
"""
ans = 0
for i in range(len(s)):
ans += (ord(s[-i-1]) - ord('A') + 1) * (26 ** i)
return ans

Java implementation

1
2
3
4
5
6
7
8
class {
public int titleToNumber(String s) {
int ans = 0;
for(int i = 0; i < s.length(); i++)
ans += Math.pow(26, i) * (s.charAt(s.length()-1-i) - 'A' + 1);
return ans;
}
}

Time complexity

O(N).

Space complexity

O(1).


171. Excel Sheet Column Number
(中文版) 算法笔记: 力扣#171 Excel表列序号