Two similar solutions with C++ perform quite differently.


  • 0
    H
    #include<math.h>
    class Solution {
    public:
        int titleToNumber(string s) {
            if(s.empty()){
                return 0;
            }
            int num=(s[0]-'A'+1)*(int)pow(26,s.length()-1);
            if(s.length()==1){
                return num;
            }
            for(int i=1;i<s.length();i++){
                num+=(s[i]-'A'+1)*(int)pow(26,(s.length()-i-1));
            }
            return num;
        }
    };
    

    The above solution only takes 4ms; however, the following one takes 8ms, which is twice as the former.
    I am quite confused and want to know why.

    #include<math.h>
    class Solution {
    public:
        int titleToNumber(string s) {
            if(s.empty()){
                return 0;
            }
            int num=0;
            for(int i=0;i<s.length();i++){
                num+=(s[i]-'A'+1)*(int)pow(26,(s.length()-i-1));
            }
            return num;
        }
    };

Log in to reply
 

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