Javascript Program To Write Your Own atoi()
Last Updated :
05 May, 2023
The atoi() function in C takes a string (which represents an integer) as an argument and returns its value of type int. So basically the function is used to convert a string argument to an integer.
Syntax:
int atoi(const char strn)
Parameters: The function accepts one parameter strn which refers to the string argument that is needed to be converted into its integer equivalent.
Return Value: If strn is a valid input, then the function returns the equivalent integer number for the passed string number. If no valid conversion takes place, then the function returns zero.
Now let's understand various ways in which one can create their own atoi() function supported by various conditions:
Approach 1: Following is a simple implementation of conversion without considering any special case.
- Initialize the result as 0.
- Start from the first character and update result for every character.
- For every character update the answer as result = result * 10 + (s[i] - '0')
JavaScript
<script>
// A simple Javascript program for
// implementation of atoi
// A simple atoi() function
function myAtoi(str)
{
// Initialize result
let res = 0;
// Iterate through all characters
// of input string and update result
// take ASCII character of corresponding digit and
// subtract the code from '0' to get numerical
// value and multiply res by 10 to shuffle
// digits left to update running total
for (let i = 0; i < str.length; ++i)
res = res * 10 + str[i].charCodeAt(0) - '0'.charCodeAt(0);
// return result.
return res;
}
// Driver code
let str = "89789";
// Function call
let val = myAtoi(str);
document.write(val);
// This code is contributed by rag2127
</script>
Time Complexity : O(N) , as only one traversal of string.
Auxiliary Space : O(1), as no extra space needed.
Approach 2: This implementation handles the negative numbers. If the first character is '-' then store the sign as negative and then convert the rest of the string to number using the previous approach while multiplying sign with it.
JavaScript
<script>
// JavaScript program for implementation of atoi
// A simple atoi() function
function myAtoi(str)
{
// Initialize result
var res = 0;
// Initialize sign as positive
var sign = 1;
// Initialize index of first digit
var i = 0;
// If number is negative, then
// update sign
if (str[0] == '-') {
sign = -1;
// Also update index of first
// digit
i++;
}
// Iterate through all digits
// and update the result
for (; i < str.length; ++i)
res = res * 10 + str[i].charCodeAt(0) - '0'.charCodeAt(0);
// Return result with sign
return sign * res;
}
// Driver code
var str = "-129";
var val=myAtoi(str);
document.write(val);
</script>
<! --This code is contributed by nirajgusain5 -->
Time complexity of the above code is O(n) where n is the length of the input string. This is because the code iterates through each character in the string and performs a constant time operation for each character.
The space complexity of the code is also O(n), where n is the length of the input string. This is because the code uses a single integer variable to store the numerical result, and this variable will have at most n digits in its binary representation. Additionally, the code does not use any additional data structures that would contribute to the space complexity.
Approach 3: This implementation handles various type of errors. If str is NULL or str contains non-numeric characters then return 0 as the number is not valid.
Approach 4: Four corner cases needs to be handled:
- Discards all leading whitespaces
- Sign of the number
- Overflow
- Invalid input
To remove the leading whitespaces run a loop until a character of the digit is reached. If the number is greater than or equal to INT_MAX/10. Then return INT_MAX if the sign is positive and return INT_MIN if the sign is negative. The other cases are handled in previous approaches.
Dry Run:

Below is the implementation of the above approach:
JavaScript
<script>
// A simple JavaScript program for
// implementation of atoi
function myAtoi(str)
{
var sign = 1, base = 0, i = 0;
// if whitespaces then ignore.
while (str[i] == ' ')
{
i++;
}
// sign of number
if (str[i] == '-' || str[i] == '+')
{
sign = 1 - 2 * (str[i++] == '-');
}
// checking for valid input
while (str[i] >= '0' && str[i] <= '9')
{
// handling overflow test case
if (base > Number.MAX_VALUE/ 10
|| (base == Number.MAX_VALUE / 10
&& str[i] - '0' > 7))
{
if (sign == 1)
return Number.MAX_VALUE;
else
return Number.MAX_VALUE;
}
base = 10 * base + (str[i++] - '0');
}
return base * sign;
}
// Driver code
var str = " -123";
// Function call
var val = myAtoi(str);
document.write(" ", val);
// This code is contributed by shivanisinghss2110
</script>
Complexity Analysis for all the above Approaches:
- Time Complexity: O(n).
Only one traversal of string is needed. - Space Complexity: O(1).
As no extra space is required.
Recursive program for atoi().
Exercise:
Write your won atof() that takes a string (which represents an floating point value) as an argument and returns its value as double.
Please refer complete article on Write your own atoi() for more details!
Similar Reads
DSA Tutorial - Learn Data Structures and Algorithms DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Quick Sort QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
Bubble Sort Algorithm Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Data Structures Tutorial Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Breadth First Search or BFS for a Graph Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Binary Search Algorithm - Iterative and Recursive Implementation Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Insertion Sort Algorithm Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Dijkstra's Algorithm to find Shortest Paths from a Source to all Given a weighted undirected graph represented as an edge list and a source vertex src, find the shortest path distances from the source vertex to all other vertices in the graph. The graph contains V vertices, numbered from 0 to V - 1.Note: The given graph does not contain any negative edge. Example
12 min read
Selection Sort Selection Sort is a comparison-based sorting algorithm. It sorts an array by repeatedly selecting the smallest (or largest) element from the unsorted portion and swapping it with the first unsorted element. This process continues until the entire array is sorted.First we find the smallest element an
8 min read