Readable C++ code within 1ms


  • 29
    Z

    class Solution {

    public:

    string convertToTitle(int n) {
    
        string res;
    
        char tmp;
    
        while(n){
    
            n -= 1;
    
            tmp = 'A' + n % 26;
    
            res = tmp + res;
    
            n /= 26;
    
        }
    
        return res;
    
    }
    

    };


  • 0
    A

    pretty neat!!!


  • 0

    I think it would be better to append the new character at the end of the string, then reverse the string just before it is returned. :)


  • 0
    S

    cool solution! but what if n <= 0 ? do you need to initialize the value of str?


  • 0
    S

    by the way, could you tell me on line 7, why not "res = res + tmp"?

    Does string append char from right to left?


  • 0
    Q

    instead of insert from front, I push_back and reverse afterwards.

    string convertToTitle(int n) {
    	string res;
    	for(;n>0;n/=26) res.push_back('A'+--n%26);
    	for(int i=0, j=res.size()-1;i<j;++i,--j) std::swap(res[i],res[j]);
    	return res;
    }

Log in to reply
 

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