![]() |
VOOZH | about |
Given a string s, 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: 0
Explanation: No digits are present, therefore 0.Input: s = " 1231231231311133"
Output: 2147483647
Explanation: The converted number is greater than 231 - 1, therefore print 231 - 1 = 2147483647.Input: s = "-999999999999"
Output: -2147483648
Explanation: The converted number is smaller than -231, therefore print -231= -2147483648.Input: s = " -0012gfg4"
Output: -12
Explanation: Nothing is read after -12 as a non-digit character 'g' was encountered.
Table of Content
Traverse the string from left to right, skipping whitespaces, handling the optional sign, and building the number digit by digit. At each step, ensure the value stays within 32-bit integer limits to avoid overflow.
How to check if the number is greater than 231 - 1 or smaller than -231 ?
The naive way is to use a data type larger than 32 bits like long or BigInteger to store the number. However, we can also use a 32-bit integer by appending the digits one-by-one and, for each digit, checking whether appending it will cause overflow.
Since we construct the number as a positive value and apply the sign at the end, we only need to check against 231 - 1. While appending a digit to the current number, we can have 3 cases:
Case 1: current number < (231 - 1)/10 then simply append the digit to the current number as it will not cause overflow.
Case 2: current number > (231 - 1)/10 then return 231 - 1 in case of overflow.
Case 3: current number = (231 - 1)/10 then in this case, only digits from 0 to 7 can be appended safely. If the next digit is greater than 7, return 231 - 1.
-12
Process the string recursively by skipping whitespaces, determining the sign, and building the number one digit at a time. At each recursive step, check for overflow and stop when a non-digit character is encountered or the string ends.
-12
Write your own atoi() that takes a string (which represents a floating point value) as an argument and returns its value as double.