Cattle off network - to prove safety office- to convert a string to an integer

(Integer.valueOf realize the function returns 0 (string), but does not meet the numerical requirements string) to a string into an integer, the request can not use the library functions integer conversion strings: Title. Value of 0 or a character string is not a valid value of 0 is returned.
Input Description:
enter a string including alphanumeric symbols, can be empty
output Description:
If the expression is valid number value is returned, otherwise 0

class Solution {
public:
    int StrToInt(string str) {
        int ans=0;
        int m=1;
        for(int i=0;i<str.size();++i)
        {
            if(i==0&&str[i]=='+'){m=1;continue;}
            if(i==0&&str[i]=='-'){m=-1;continue;}
            if(str[i]>='0'&&str[i]<='9')
            {
                ans=10*ans+str[i]-'0';
            }
            else{
                return 0;
            }
        }
        return m*ans;
    }
};

Guess you like

Origin blog.csdn.net/qq_43387999/article/details/91370671