Excel Sheet Column Title
https://leetcode.com/problems/excel-sheet-column-title/description/
Given a positive integer, return its corresponding column title as appear in an Excel sheet.
Thoughts
本质上是进制转换, 只是这里是26进制. 26进制余数可以取0 ~ 25, 但由于结果要求从1~26, 因此每次要减1.
举个例子, 28 = AB, 如果不-1取余得到2, 2 + A = C, 然后28 / 26 = 1, 再对26取余得到B, 即BC. 因此我们要每次都对n - 1.
Code
class Solution {
public String convertToTitle(int n) {
StringBuilder sb = new StringBuilder();
while (n > 0) {
n--;
sb.insert(0, (char)('A' + n % 26));
n /= 26;
}
return sb.toString();
}
}
Analysis
时空复杂度O(lgN).
Last updated
Was this helpful?