Two one line cpp recursive solutions

  • 0

    solution A: Process the first char of the string firstly , then process the others recursively:

    return s!=""?pow(26,s.size()-1)*(s[0]-64)+titleToNumber(s.substr(1)):0;

    solution B: Process the last char of the string firstly, then process the remains recursively:

    return s!= ""?26*titleToNumber(s.substr(0,s.size()-1))+s[s.size()-1] -64:0;

    Then which one is better? OJ shows that the first one's runtime is 14ms, second is 16ms in my computer. Personally, I prefer the first one which matches my mind better.

  • 0


    int titleToNumber(char* s, int cn) { 
        return *s ? cn : titleToNumber(s + 1, cn * 26 + *s - 'A' + 1);

Log in to reply

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