Normalize Number String
Python
Hard
3 views
Problem Description
A number is provided as string. It may have + sign, leading zeros, and decimal part. Normalize it: remove +, remove extra leading zeros, remove trailing zeros in decimal, and if it becomes -0 or 0.0 then output 0.
Input Format
One number as string.
Output Format
One normalized string.
Official Solution
import sys
s=sys.stdin.read().strip()
if not s: sys.exit(0)
neg=False
if s[0]=='+':
s=s[1:]
elif s[0]=='-':
neg=True
s=s[1:]
if '.' in s:
a,b=s.split('.',1)
else:
a,b=s,''
a=a.lstrip('0')
if a=='':
a='0'
if b!='':
b=b.rstrip('0')
res=a
if b!='':
res=a+'.'+b
if res=='0' or res=='0.':
res='0'
if res=='0':
sys.stdout.write('0')
else:
sys.stdout.write(('-' if neg else '')+res)
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!