Share my simple solution, just a little trick to handle corner case 26


  • 44
    S
    string convertToTitle(int n) {
            string ans;
            while (n) {
                ans = char ((n - 1) % 26 + 'A') + ans;
                n = (n - 1) / 26;
            }
            return ans;
        }

  • 1
    Q

    successively insert from the front of string is not good style, though in this case the size is quite small.
    push_back and reverse would be better.

    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;
    }

  • 0
    L
    class Solution {
    public:
        string convertToTitle(int n) {
            string res="";
            while(n>0)
            {
                if(n%26==0) 
                {
                    res="Z"+res;
                    n=n/26-1;
                }
                else
                {
                    res= (char)(n%26+'A'-1)+res;
                    n=n/26;
                }
                    
                
            }
            return res;
        }
    };
    

Log in to reply
 

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