How is this test case failing?

  • 0

    I don't understand how I am failing with the input of 27.

    my code (cpp) is ...

    class Solution {
        string convertToTitle(int n) {
                return "";
            return convertToTitle(n/27) + (char)('A' + --n%26);

    It is pretty similar to the two liner java code that was posted here, except for the convertToTitle((n-1)/26)) part, but even when I do that I get the output of "A" instead of "AA". I walked through it by hand and I think my answer is right but I guess I'm missing something.

  • 1

    (n-1)/26 is not the problem. the problem is --n % 26. I think in c++ the --n is evaluates first, so value that is sent into the recursion is already processed with the decrement operator. Following two variations should work fine:

    return convertToTitle(n / 26) + (char)('A' + (--n % 26));
    return convertToTitle((n-1) / 26) + (char)('A' + ((n-1) % 26));

  • 0

    Oh dang it. You are totally right. Somehow i thought that it would predecrement only when it got to the --n not before it did anything else... thank you.

  • 0

    Thanks for voting as best answer. I think C/C++ compilers parse it from right to left. That is why this behavior. In my opinion we should try to write code such that it avoids such compiler specific behavior as much as possible. In this case it can be avoided by breaking up the code to 2 parts. 1st part just calls the recursion and collects the result. 2nd part does the combining of result. for example: r = convertToTitle(--n/26); return r + (char)('A' + (n % 26));

Log in to reply

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