Programming Question : Leetcode-8

Raj shukla
1 min readMar 30, 2021

--

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.

Code:

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

No responses yet

Write a response