The solution which beats 100% cpp coders


  • 0
    B
    class Solution 
    {
    public:
    int myAtoi(string str) 
    {
        long long ret=0;
        bool neg=false;
        int startIdx=0;
        while(startIdx<str.size() &&str[startIdx]==' ')
        {startIdx++;}
        if(startIdx==str.size()){return 0;}
        
        if(str[startIdx]=='-'){neg=true;startIdx++;}
        else if(str[startIdx]=='+'){neg=false;startIdx++;}
        for(int i=startIdx;i<str.size();i++)
        {
            if(str[i]<'0' || str[i]>'9')break;
            else
            {
                ret*=10;
                ret+=str[i]-'0';
                if(neg && -ret<=INT_MIN){return INT_MIN;}
                if(!neg && ret>=INT_MAX){return INT_MAX;}
            }
        }
        return neg?(-ret):ret;
    }
    };

  • 0
    J

    hey, i have used your code to test the complier for that I can't find ang bug in my code but it haven't passed and then I have tried so many times even reference your code,but it still can't be passed, so i think the complier was wrong or I should haven't understand the request well,I had given up, whatever,thank you for the code for the complier test.


  • 0
    B

    Maybe you need some additional code.Below is my successful complied and tested code in Visual Studio 2005.

    //some necessary head files
    #include<string>
    #include<iostream>
    using namespace std;
    class Solution 
    {
    public:
    	int myAtoi(string str) 
    	{
        	long long ret=0;
    	    bool neg=false;
    		int startIdx=0;
        	while(startIdx<str.size() &&str[startIdx]==' ')
    	    {startIdx++;}
    		if(startIdx==str.size()){return 0;}
    
    		if(str[startIdx]=='-'){neg=true;startIdx++;}
    		else if(str[startIdx]=='+'){neg=false;startIdx++;}
    		for(int i=startIdx;i<str.size();i++)
    		{
    			if(str[i]<'0' || str[i]>'9')break;
    			else
    			{
    				ret*=10;
          			ret+=str[i]-'0';
        			if(neg && -ret<=INT_MIN){return INT_MIN;}
        			if((!neg) && ret>=INT_MAX){return INT_MAX;}
    		    }
    	    }
    	    return neg?(-ret):ret;
        }
    };
    //Below is for testing the myAtoi function
    void main()
    {
    	Solution s;
        string str;
        while(cin>>str)
        {
    	    //we add 2 to the result to ensure the convertion is successfully completed
    	    cout<<s.myAtoi(str)+2<<endl;
        }
    }

  • 0
    J

    thanks,i complied the code in gnu 4.9.2 with Ubuntu 14.04,anyway thanks for the test


Log in to reply
 

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