One line in C++ enclosed with its iterative version


  • 1

    The key point here is to make n start from 0 instead of 1 then everything else is that simple and intuitive.

    class Solution {
    public:
        string convertToTitle(int n) 
        {
            return ((n-1)/26? convertToTitle((n-1)/26) : "") + string(1, 'A'+(n-1)%26);   
        }
    };
    

    iterative method

    class Solution {
    public:
        string convertToTitle(int n) {
            string s;
            while(n)
            {
                s += 'A'+(n-1)%26;
                n = (n-1)/26;
            }
            reverse(s.begin(), s.end());
            return s;
        }
    };
    

Log in to reply
 

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