# How to write your own atoi function in C++

Hello Friends, Today we are going to learn how to write atoi function in C++. First, understand about atoi function then we will see an example and then we will see the implementation part.

Atoi() function converts a string into an integer. It takes one argument as an input in the form of string and returns an integer if inputs are valid. I will tell you which type of strings is valid using examples. Let’s see an example:

Example 1: Input =”123″ Output = 123

Example 2: Input =”23a” Output = -1

Example 3: Input =”-12″ Output = -12

We can see that example 1 and example 3 are valid whereas example 2 are invalid because one of the characters in the string is alphabet.

Now I will show you how to implement this and then we will understand the algorithm.

## C++ code for implementing own atoi function

Input is in the form of string and output should be an integer.

Time Complexity = O(n)

#include <bits/stdc++.h> using namespace std; int atoi(string str); int main() { string s; //suppose input is "246" cin>>s; cout<<atoi(s)<<endl; } int atoi(string str) { int answer=0,temp,mark=0,i=0; int n = str.length(); int count=n-1; if(str[0]=='-') { mark=1; i++; count=n-2; } for(i;i<n;i++) { if(str[i]-0>=48 && str[i]-0<=57) { temp= pow(10,count); answer=answer+temp*(str[i]-48); count--; } else return -1; } if(mark==0) return answer; if(mark==1) return answer*(-1); }

Output : 246

### Understanding the Algorithm

In this code, we will use ascii value of character. We will start reading the character from the left one by one till the end. If ascii value of the character is lying between 48 and 57 then it is valid otherwise it is invalid. After that, we will subtract the character ascii value with 48 to get the digit and then we will use the digit to form the number.

## Leave a Reply