C++ | Using vector and booleans | No string stream

programming
Tags: #<Tag:0x00007f2435666ad8>

#1
int Solution::atoi(const string A) {
if(A.size() == 0) return 0; // Null string

int i=0;
while(i<A.size() && A[i] == ' ') i++; // removing white spaces at the front
if(i == A.size()) return 0; // When the string only contains white spaces

vector<int> digit; // For storing digits

bool neg = true; // For first character to be negative
bool pos = true; // For first character to be positive
bool n = false; // negative is present (initially set to false)
bool p = false; // positive is present (initially set to false)

for(i;i<A.size();i++){
    if(A[i] >= '0' && A[i] <= '9'){
        digit.push_back(A[i]-'0'); 
       //Now if neg or pos is not found set them as false
       //If either of them is found, one of the below two loops will set them to false and the respective found boolean ( n or p) to true
        if(neg) neg = false; 
        if(pos) pos = false;
    }
    else if(A[i] == '-' && neg){
        n = true;
        neg = false;
        pos = false;
    }
    else if(A[i] == '+' && pos){
        p = true;
        pos = false;
        neg = false;
    }
    else break;
}

  ///Now from the vector elements we compute the digit.
 /// Ex: 1,2,3 && n = false: 1x10^2 + 2x10^1 + 3x10^0 = 123
 /// Ex: 1,2,3 && n = true: -1x10^2 - 2x10^1 - 3x10^0 = -123
int m = digit.size();

long long num = 0;

for(int i=0;i<m;i++){
    if(n){
        num -= ((pow(10,m-i-1))*digit[i]);
    }
    else{ ///////////////// else if(p) or else , you can use any of them here
        num += ((pow(10,m-i-1))*digit[i]);
    }
    if(num > INT_MAX) return INT_MAX;
    if(num < INT_MIN) return INT_MIN;
}

return num;

}