Excel Sheet Column Title

Challenge 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 1:

Input: 1
Output: "A"

Example 2:

Input: 28
Output: "AB"

Solution

This is a algorithm to convert a decimal number into a 26-based number.

There is a special case: n % 26 == 0.

class Solution {
public:
    string convertToTitle(int n) {
        string res = "";
        while(n > 0) { 
            if(n >= 1 && n <= 26) { 
                res += ('A' + n - 1);
                break;
            } else if (n % 26 == 0) {
              res += 'Z';
              n -= 26;
            } else { 
                res += ('A' + n%26 - 1);
            }
            n /= 26;
        }
        reverse(res.begin(), res.end());
        return res;
    }
};
Last Updated on

Leave a Reply

Your email address will not be published. Required fields are marked *