168 Excel Sheet Column Title Excel表列名稱
Description:
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
...
Example:
Example 1:
Input: 1
Output: "A"
Example 2:
Input: 28
Output: "AB"
Example 3:
Input: 701
Output: "ZY"
題目描述:
給定一個正整數(shù),返回它在 Excel 表中相對應(yīng)的列名稱瓜饥。
例如巡莹,
1 -> A
2 -> B
3 -> C
...
26 -> Z
27 -> AA
28 -> AB
...
示例:
示例 1:
輸入: 1
輸出: "A"
示例 2:
輸入: 28
輸出: "AB"
示例 3:
輸入: 701
輸出: "ZY"
思路:
不斷取 26的余數(shù)和商即可, 注意邊界條件
時間復(fù)雜度O(logn), 空間復(fù)雜度O(1)
代碼:
C++:
class Solution
{
public:
string convertToTitle(int n)
{
string result = "";
while (n)
{
n--;
result += n % 26 + 'A';
n /= 26;
}
reverse(result.begin(), result.end());
return result;
}
};
Java:
class Solution {
public String convertToTitle(int n) {
return n == 0 ? "" : convertToTitle(--n / 26) + (char)(n % 26 + 'A');
}
}
Python:
class Solution:
def convertToTitle(self, n: int) -> str:
return self.convertToTitle((n - 1) // 26) + chr((n - 1) % 26 + ord('A')) if n else ""