String to Integer Parser
Programming Interview
Medium
5 views
Problem Description
A string s is provided (maybe with leading spaces and sign). Parse first integer like simple atoi. If no number, output 0.
Output Format
One integer.
Official Solution
import sys
s=sys.stdin.read()
if s is None: sys.exit(0)
if s.endswith('\
'):
s=s[:-1]
i=0
n=len(s)
while i<n and s[i]==' ':
i+=1
sign=1
if i<n and (s[i]=='+' or s[i]=='-'):
if s[i]=='-':
sign=-1
i+=1
val=0
found=False
while i<n and '0'<=s[i]<='9':
found=True
val=val*10 + (ord(s[i])-48)
i+=1
sys.stdout.write(str(sign*val if found else 0))
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!