試題請參見: https://oj.leetcode.com/problems/excel-sheet-column-title/
題目概述
Given a positive integer, return its corresponding column title as appear in an Excel sheet.
For example:
1 -> A
2 -> B
3 -> C
...
26 -> Z
27 -> AA
28 -> AB
解題思路
不斷對26取餘數, 計算直至n == 0.
例如:
- 初始n = 28
- 先計算 (n - 1) % 26的值 (= 1), 則當前位爲B.
- n /= 26 (此時 n == 1)
- 再計算 (n - 1) % 26的值 (= 0), 則當前位爲A.
- 則最終結果爲AB.
遇到的問題
By one mistake: 各種邊界問題
設想n == 26的情況. 循環的終止條件爲 n == 0.
當n == 26時, 計算完n /= 26時的結果爲1. 不滿足循環終止條件, 會再次進入第2次循環, 使得最終輸出結果爲AZ.
因此需要對這種情況做特殊處理.
源代碼
class Solution {
public:
std::string convertToTitle(int n) {
std::string columnTitle;
if ( n <= 0 ) {
return columnTitle;
}
char currentChar = 0;
while ( n != 0 ) {
currentChar = 'A' + ((n - 1) % 26);
columnTitle = currentChar + columnTitle;
if ( n == 26 ) {
break;
} else {
n = (n - 1) / 26;
}
}
return columnTitle;
}
};