Normalize Number String

Normalize Number String

Hard Programming Interview Data Structures 16 views
Explanation Complexity

Problem Statement

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.

Example

+0012.3400
12.34

Constraints

Input length

Input / Output Format

Input Format
One number as string.
Output Format
One normalized string.
Constraints
Input length

Examples

Input:
+0012.3400
Output:
12.34

Example Solution (Public)

Programming Interview
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)

Official Solution Code

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)
Please login to submit solutions.
Editor
Output

                                        
Please login to submit solutions.