來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/excel-sheet-column-number
題目描述:
給定一個Excel表格中的列名稱,返回其相應(yīng)的列序號。
例如,
A -> 1
B -> 2
C -> 3
...
Z -> 26
AA -> 27
AB -> 28
...
示例 1:
輸入: "A"
輸出: 1
示例 2:
輸入: "AB"
輸出: 28
示例 3:
輸入: "ZY"
輸出: 701
思路:
- 將16進(jìn)制數(shù)abc,轉(zhuǎn)成10進(jìn)制,我們是怎么做的呢,
第0位的全值為16的0次方,第1位的權(quán)值為16的1次方,第2位的權(quán)值為16的2次方...第n位的權(quán)值為16的n次方。將各個位的數(shù)字乘以位權(quán),然后再相加,就得到了十進(jìn)制形式。
c * 16^0 + b * 16 ^ 1 + c * 16^2
用代碼表達(dá)出來也就是
String columnTitle = "abc";
int index = 0;
for (int i = 0; i < columnTitle.length(); i++) {
index = index * 16 + Integer.valueof(columnTitle.charAt(i) + "");
}
return index;
把上面的for循環(huán)展開 (((0 * 16) + a) * 16 + b) * 16 + c = c * 16^0 + b * 16 ^ 1 + c * 16^2
本題本質(zhì)上也是一個進(jìn)制轉(zhuǎn)換題,只不過不是16進(jìn)制轉(zhuǎn)10進(jìn)制,而是26進(jìn)制轉(zhuǎn)10進(jìn)制,需要注意的一點就是,'A'上從1開始的,因此常數(shù)項需要加上1.
代碼實現(xiàn):
class Solution {
public int titleToNumber(String columnTitle) {
int index = 0;
for (int i = 0; i < columnTitle.length(); i++) {
index = index * 26 + (columnTitle.charAt(i) - 'A' + 1);
}
return index;
}
}