4-line iterative C++ O(log n) solution (0 ms)


  • 0

    The idea is to represent any positive integer n = sum_i a[i]*26^i, where i >= 0and a[i] in [1, 26]. Then convert a[i]to char 'A' + a[i] - 1and build the string backward.

        string convertToTitle(int n) {
          string res;
          while (n > 0) { res += 'A' + (n-1)%26; n = (n - 1)/26; }
          reverse(res.begin(), res.end());
          return res;
        }
    

Log in to reply
 

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