168. Excel Sheet Column Title

1. 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 
...

2. Example

Example 1:
Input: 1
Output: “A”

Example 2:
Input: 28
Output: “AB”

Example 3:
Input: 701
Output: “ZY”

3. Solutions

My Accepted Solution

n = number
Time complexity: O(n)
Space complexity: O(n)

// we can't treat this problem to 26 scale number system, compared to decimalism
// since it does not have 'zero', A is 1, but not 0
// but it have 26 letters, so it is 26 scale number system rather than 27
// for decimalism, 10 will result in a carry, so it is 10
// for this problem, 26 will not result in a carry, it is 'Z', rather than A0, since it doesn't have '0'
// 26 should not result in a carry, but it should convert to a number with 0, since we have to add 'A'
// so, we could solve these two problems by decrease the number by one

class Solution 
{
public:
    string convertToTitle(int number) 
    {
        if(number == 0) return string("");
        
        return convertToTitle(--number / 26) + (char)(number % 26 + 'A');
    }
};
Last updated:
Tags: Math
comments powered by Disqus