Friday, July 15, 2016

roman numeral to int, int to roman numeral

xviii = iixx = 18
mcmlcv = 1955

rtoi:
int rtoi(s):
    if s == null:
        throw
    n = 0
    maxvalue = 0
    for r in s.reverse():
        value = rtoimap[r]
        if value >= maxvalue:
            maxvalue = value
            n += value
        else:
            n -= value
    return n

rtoimap = 
i    1
v    5
x   10
l   50
c  100
d  500
m 1000
[Hat tip to B]

itor:
string itor(n):
    if n < 0:
        throw
    buffer = new
    while n >= 1000:
        buffer.append("m")
        n -= 1000
    // below 1000
    n100 = (n /100) *100
    buffer.append(itormap[n100])
    n -= n100
    // below 100
    n10 = (n /10) *10
    buffer.append(itormap[n10])
    n -= n10    
    // below 10
    n1 = n
    buffer.append(itormap[n1])
    n -= n1
    // n is 0
    return buffer.tostring()

itormap =
  0 "" //empty
  1 i
  2 ii
  3 iii
...
  9
 10 x
 20 xx
...
 90 xc
100 c
200 cc
...
900 cm

No comments:

Post a Comment