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
String to Integer - Write your own atoi()
Given a string s, the task is to convert it into integer format without utilizing any built-in functions. Refer the below steps to know about atoi() function.Examples:Input: s = "-123"Output: -123Input: s = " -"Output: 0Explanation: No digits are present, therefore 0.Input: s = " 1231231231311133"Ou
7 min read
Program to Encrypt a String using ! and @
Given a string, the task is to encrypt this string using ! and @ symbols, alternatively. While encrypting the message the encrypted format must repeat the symbol as many times as the letter position in Alphabetical order. Examples: Input: string = "Ab" Output: !@@ Explanation: Position of 'A' in alp
11 min read
Program to print the arrow pattern
Given the value of n, print the arrow pattern.Examples : Input : n = 5 Output : * ** *** **** ***** **** *** ** * Input : n = 7 Output : * ** *** **** ***** ****** ******* ****** ***** **** *** ** * Below is the program to print the arrow pattern: C++ // C++ program to print the // arrow pattern #in
10 min read
Program to implement ASCII lookup table
ASCII stands for American Standard Code for Information Interchange. Computers can only understand numbers, so an ASCII code is the numerical representation of a character such as âaâ or â@â or an action of some sort. ASCII lookup table is a tabular representation of corresponding values associated
7 min read
Program for Arrow Star Pattern
Given the value of n, print the pattern.Examples : Input : 5 Output : ***** **** *** ** * ** *** **** ***** Input : 7 Output : ******* ****** ***** **** *** ** * ** *** **** ***** ****** ******* Below is the implementation to print the above pattern : C++ // C++ Implementation to print the pattern #
6 min read
Program to print V and inverted-V pattern
Inverted V pattern: Given the value of n, print the inverted V pattern.Examples : Input : n = 5 Output : E D D C C B B A A Input : n = 7 Output : G F F E E D D C C B B A A Below is the program to print the above pattern C++ // C++ Implementation to print the pattern #include <bits/stdc++.h> us
8 min read
Output of Java Programs | Set 52 (Strings Class)
Prerequisite : Basics of Strings class in java 1. What is the Output Of the following Program Java class demo1 { public static void main(String args[]) { String str1 = "java"; char arr[] = { 'j', 'a', 'v', 'a', ' ', 'p', 'r', 'o', 'g', 'r', 'a', 'm', 'm', 'i', 'n', 'g' }; String str2 = new
5 min read
Some important shortcuts in Competitive Programming
One of the best ways to save time in competitive programming is by creating snippets. Snippets are reusable pieces of code that can be used easily for program creation or repeated tasks. It not only eases the efforts put into writing any code but also saves time for debugging as you know that is sto
2 min read
Nashorn JavaScript Engine in Java with Examples
Nashorn: Nashorn is a JavaScript engine which is introduced in JDK 8. With the help of Nashorn, we can execute JavaScript code at Java Virtual Machine. Nashorn is introduced in JDK 8 to replace existing JavaScript engine i.e. Rhino. Nashorn is far better than Rhino in term of performance. The uses o
4 min read
Print N to 1 without loop
You are given an integer N. Print numbers from N to 1 without the help of loops. Examples: Input: N = 5Output: 5 4 3 2 1Explanation: We have to print numbers from 5 to 1. Input: N = 10Output: 10 9 8 7 6 5 4 3 2 1Explanation: We have to print numbers from 10 to 1. Approach: If we take a look at this
3 min read