[剑指 offer] JT49---Convert a string to an integer (requires not to use library functions!)

Sword Finger Offer Question 49

The topic is as follows

Insert picture description here

Idea and code

The idea is very simple.
First judge whether there is a sign bit, but the second sign bit is definitely wrong!
Then read the number string and add it to the end of the number. The
offer is not as difficult as you think! ! !

class Solution {
    
    
public:
    int StrToInt(string str) {
    
    
        if(str.length()==0) return false;
        int flag=0;
        long res=0;
        for(auto i:str){
    
    
            if(i>'9'||i<'0'){
    
    
                if(flag==0&&i=='-') flag=-1;
                else if(flag==0&&i=='+') flag=1;
                else return false;
            }else{
    
    
                res=res*10+i-'0';
            }
        }
        if(flag==-1) return -res;
        else      return  res;
    }
};

Insert picture description here

Guess you like

Origin blog.csdn.net/qq_42136832/article/details/115111793