0

I'm trying to convert the Roman Numeral to decimal number. I am successfully converting roman numeral to decimal but I want to add a functionality that if entered roman numeral is correct or not??

I'm using switch case for letters M,D,C,L,X,V,I to convert into decimal. So What should be my approach to validate the Roman Numeral I'm using Swift 4.0.

switch char
        {
        case "M":
            decimal = processDecimal(decimal: 1000, lastNumber: lastnumber, lastDecimal: decimal)
            lastnumber = 1000
        case "D":
            decimal = processDecimal(decimal: 500, lastNumber: lastnumber, lastDecimal: decimal)
            lastnumber = 500
        case "C":
            decimal = processDecimal(decimal: 100, lastNumber: lastnumber, lastDecimal: decimal)
            lastnumber = 100
        case "L":
            decimal = processDecimal(decimal: 50, lastNumber: lastnumber, lastDecimal: decimal)
            lastnumber = 50
        case "X":
            decimal = processDecimal(decimal: 10, lastNumber: lastnumber, lastDecimal: decimal)
            lastnumber = 10
        case "V":
            decimal = processDecimal(decimal: 5, lastNumber: lastnumber, lastDecimal: decimal)
            lastnumber = 5
        case "I":
            decimal = processDecimal(decimal: 1, lastNumber: lastnumber, lastDecimal: decimal)
            lastnumber = 1
        default:
            print("Nothing")
        }
    }
    print("Decimal Number is:\(decimal)")
}

func processDecimal(decimal: Int, lastNumber: Int, lastDecimal: Int) -> Int
if lastNumber>decimal
{
    return lastDecimal-decimal
}
else
{
    return  lastDecimal + decimal
}
rmaddy
  • 307,833
  • 40
  • 508
  • 550
Viren Patel
  • 118
  • 1
  • 11
  • Maybe I'm missing something? If you are successfully parsing Roman numerals then you must already have designed and coded an algorithm to implement at least some of the rules, e.g. to correctly parse `I`, `V`, `IV` and `VI`. Just extend your algorithm to cover any rules you are currently not checking. – CRD Mar 11 '18 at 21:04
  • This is the code I'm using but it does not have validation. For example If I give CCMMDD as input it return 3000 but it is not valid roman numeral – Viren Patel Mar 11 '18 at 21:13

0 Answers0