Your task is to implement the function atoi. The function takes a string(str) as argument and converts it to an integer and returns it.
Note: You are not allowed to use inbuilt function.
123
123
class Solution {
public:
int atoi(string str) {
int num = 0, fact = 1;
if(str[0] == '-') {
fact = -1;
str = str.substr(1);
}
for(char c: str) {
if(c - '0' < 0 || c - '0' > 9) {
num = -1;
fact = 1;
break;
}
num = num * 10 + c - '0';
}
return num * fact;
}
};