Excel Sheet Column Title: 0ms


  • 0
    H
    class Solution {
    public:
        string convertToTitle(int n) {
                string str;
    	   int tmp;
           if(n<=0)
                 return "";
    
    	   while(n)
    	   {
    			tmp=n%26;
    			n/=26;
    			if(tmp)
    				str.push_back(tmp-1+'A');
    			else
    			{
    				str.push_back('Z');
    				n--;
    			}
    	   }
    	   if(str.size()>1)
    			reverse(str.begin(),str.end());
    
    	   return str;
        }
    };

  • 0
    S

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


  • 0
    H

    Thank you for your advice.


  • 0
    Z

    class Solution {
    public:
    string convertToTitle(int n) {
    string str;
    int tmp;
    if(n<=0)
    return "";

       while(n)
       {
            tmp=n%26;
            n/=26;
            if(tmp)
                str.push_back(tmp-1+'A');
            else
            {
                str.push_back('Z');
                n--;
            }
       }
       if(str.size()>1)
            reverse(str.begin(),str.end());
    
       return str;
    }
    

    };


Log in to reply
 

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