A concise solution for Excel Sheet Column Title


  • 0
    M
    class Solution {
    public:
        string convertToTitle(int n) {
            string res;
            const int maxlen = 1000;
            char tmpchar[maxlen];
            memset(tmpchar, 0, sizeof(tmpchar));
            long long b = 26;
            int tmpcharidx = 0;
            while(n > 0){
                int r = n % 26;
                if(r == 0){
                    tmpchar[tmpcharidx++] = 'Z';
                    n -= 26;
                }
                else{
                    tmpchar[tmpcharidx++] = 'A' + r - 1;
                    n -= r;
                }
                n /= 26;
            }
            for(int k = tmpcharidx - 1; k >= 0; --k){
                res += tmpchar[k];
            }
            return res;
        }
    };
    

    2ms solution


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.