[C++]Just a problem of base conversion


  • 5
    G

    Convert base10/demical number n into "base26" string.

    (Note that there is no "zero" in A~Z, thus we regard it base26 instead of base27).

    1~26 represent A~Z separately. 27 represents "AA".
    While in common presentation of baseX(binary, octal, ...), 27 should represent "A0".

    The peoblem can be easily solved by iteration of "mod 26 and divided by 26".

    class Solution {
    public:
        string convertToTitle(int n) {
            if(n < 1)
                return "";
            else
            {
                string result = "";
                while(n)
                {//get every letter in n from right to left
                    n --;
                    char c = n%26 + 'A';
                    result += c;
                    n /= 26;
                }
                reverse(result.begin(), result.end());
                return result;
            }
        }
    };

Log in to reply
 

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