Programming Question : Leetcode-8
Approach for solving Leetcode Question — String to Integer (atoi)
For solving this question, we should know some things which python uses(I am coding in python :) )
a) for ignoring spaces in any string, python uses strip function as str.strip() that will remove all the leading or trailing whitespaces(or simply spaces) from string.
b) if we substract ascii value of 0 from any integer’s ascii value , that will give the integer. Example : ord(‘10’) — ord(‘0’) = 10 and ord(‘34’)-ord(‘0’) = 34, with this we can convert any string to integer.
c) for converting any number from string to integer, I have used method as ,multiply each value with 10 and add the next value of string (after changing to integer) to it. Example “543” can be converted as:
5*10 + 4 = 54 => 54 *10 + 3 = 543
Now , we have to look at some edge cases which you can see and understand in starting of the code itself.
d) first I have converted the 0th digit to integer and then loop through first to last digit converting all the string to integer.
e) Return the value according to the changed integer.