Simple C++ code


  • 2
    L
    class Solution {
    public:
        string convertToTitle(int n) {
            if (n == 0) return "";
            int r = (n-1)%26;
            char c = r+'A';
            return convertToTitle((n-r)/26)+c;
        }
    };

  • 4
    S
    class Solution {
    public:
        string convertToTitle(int n) {
            string result = "";
            while (n) {
                result += (--n % 26) + 'A';
                n /= 26;
            }
            return string(result.rbegin(), result.rend());
        }
    };

  • 0
    M
    This post is deleted!

  • 0
    T

    A small optimization: use string.insert here to avoid creating temporary string object.

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

Log in to reply
 

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