Leetcode--Roman to Integer

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.