Egbert Lin's Blog

“Life is not a race, but a journey to be savoured each step of the way” by Brian Dyson

[LeetCode Road] Excel Sheet column Title - Solution/C++

168. Excel Sheet Column Title

Question:

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:

Input: 1
Output: "A"

Input: 28
Output: "AB"

Input: 701
Output: "ZY"

Source code:

Version 1

Idea:
According to the ASCII talbe, if you want to get A~Z character, you need 65-90 demical number to convert it.

If the input is n = 26, you use %26 to get the remainder is zero, then it is converted to character you will attain 'A', but a correct answer is 'Z'. So, n minus 1 is important before you get the remainder at 6 line.

Next step, you can convert int to character directly. Notice: +65 is same as 'A'.
At 8 line, (n - 1)/26 as a carry condition every time until n will be 0.

1
2
3
4
5
6
7
8
9
10
11
12
class Solution {
public:
string convertToTitle(int n) {
string res = "";
while(n != 0){
int remainder = (n - 1) % 26;
res = (char)(remainder + 65) + res;
n = (n - 1)/26;
}
return res;
}
};