Sunday, January 18, 2015

[Leetcode] Excel Sheet Column Title

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 
Analysis:
Similar to the problem of "Excel Sheet Column Number", we want to represent a number with 26 as base. The code is almost exactly same as converting a decimal number to string, eg: 1234 -> "1234", except that it is 26 base and beginning from 1 rather than 0 (decimal begins from 0 as 0-9). 


    string convertToTitle(int n) {
        string str = "";
        int k = 26;
        while(n > 0)
        {
            str.insert(str.begin(), (n - 1) % k + 'A');
            n = (n - 1) / k;
        }
        
        return str;
    }

No comments:

Post a Comment