Skip to content

Latest commit

 

History

History
43 lines (36 loc) · 1.04 KB

implement-atoi.md

File metadata and controls

43 lines (36 loc) · 1.04 KB

Implement Atoi

Problem Link

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.

Sample Input

123

Sample Output

123

Solution

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;
    }
};

Accepted

image