168-excel-sheet-column-title
Question
https://leetcode.com/problems/excel-sheet-column-title/description/
Given a positive integer, return its corresponding column title as appear in an Excel sheet.
Example:
1 -> A
2 -> B
3 -> C
...
26 -> Z
27 -> AA
28 -> AB
Thought Process
- Mod
- we need to use mod to get the correct character
- Reverse the string at the end
- Time complexity O(log n)
- Space complexity O(1)
Solution
class Solution {
public String convertToTitle(int n) {
StringBuilder sb = new StringBuilder();
while (n > 0){
n--;
sb.append((char)('A' + n % 26));
n /= 26;
}
return sb.reverse().toString();
}
}