C++ 0ms 2 solutions


  • 0
    Z
    class Solution {
    public:
    string convertToTitle(int n) {
        //return solution1(n);    //recursive
        return solution2(n);    //iterative
    }
    private:
    string solution1(int n){
        string s;
        if(!n) return s;
        int rem = (n - 1) % 26 + 1;
        s = solution1((n - rem) / 26) + (char)(rem + 64);
        return s;
    }
    string solution2(int n){
        string s;
        if(!n) return s;
        int rem;
        while(n){
            rem = (n - 1) % 26 + 1;
            s.insert(s.begin(), (char)(rem + 64));
            n = (n - rem) / 26;
        }
        return s;
    }
    };

Log in to reply
 

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