Title Description:
Given a Roman numeral, convert it to an integer.
Input is guaranteed to being within the range from 1 to 3999.
is to convert Roman numerals into integers.
1. First understand the integer corresponding to the Roman numerals:
CharacterIVXLCDM
Digital1510501005001000
2. Conversion rules
In Roman string S, for S[i] and s[i+1], if the s[i+1] number is small, then the integer is s[i]+s[i+1], otherwise:
If S[I+1] is larger than s[i], then s[i] and s[i+1] represent s[i+1]-s[i].
Ideas:
Traverse Roman string s, each mapped to a character, total initialized to s[0],i∈[0,n), compare s[i] and s[i+1], if the latter is directly cumulative s[i+1], otherwise subtract s[i] twice times and add the current number s[i+1].
Implementation code:
public class Solution {public int romantoint (string s) { if (string. IsNullOrEmpty (s)) { return 0; } var len = s.length; var result = Convert (S[0]); if (Len < 2) { return result; } for (var i = 1;i < Len; i++) { var pre = Convert (S[i-1]); var current = Convert (S[i]); if (current <= pre) { result + = current; } else{ result = result-2 * pre + current; } } return result; } private int Convert (char c) {switch (c) {case ' I ': return 1;case ' V ': Return 5;case ' X ': return; Case ' L ': return; Case ' C ': return; Case ' D ': return; Case ' M ': return; Default:throw new ArgumentException ();}}}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Leetcode--Roman to Integer