此篇文章為我的解題紀錄,程式碼或許並不是很完善

Leetcode - 171. Excel Sheet Column Number

解題思路

從最左邊開始逐一運算,將char轉換成ascii code後乘上26的次方

我滴程式碼

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
public:
int titleToNumber(string columnTitle) {
int size = columnTitle.length() - 1;
int sum = 0;
while(size > -1)
{
sum += pow(26, size)*((columnTitle[columnTitle.length() - 1 - size] - 'A') + 1);
size--;
}

return sum;
}
};
1
2
3
4
5
6
7
8
9
10
class Solution:
def titleToNumber(self, columnTitle: str) -> int:
length = len(columnTitle)
size = length - 1
sum = 0
while(size > -1):
sum = sum + math.pow(26, size) * int( ord(columnTitle[length - 1 - size]) - 64 )
size = size - 1

return int(sum)