zoukankan      html  css  js  c++  java
  • Leetcode题目:Roman to Integer

    题目:Given a roman numeral, convert it to an integer.

    Input is guaranteed to be within the range from 1 to 3999.

    解题思路:罗马数字的构成规则是:

    1. 相同的数字连写,所表示的数等于这些数字相加得到的数,如 Ⅲ=3;
    2. 小的数字在大的数字的右边,所表示的数等于这些数字相加得到的数,如 Ⅷ=8、Ⅻ=12;
    3. 小的数字(限于 Ⅰ、X 和 C)在大的数字的左边,所表示的数等于大数减小数得到的数。

    所以解题的时候,我们就一直加,加到出现左边这个数字比右边这个数字小的时候,再减去他。因为之前加过他一次,所以减去的时候,需要减去两次。

    代码为:

    class Solution {
    public:
        int romanToInt(string s) {
            int slen = s.length();
            if(slen <= 0)
                return 0;
            char s_copy[slen + 1];
            strncpy(s_copy,s.c_str(),slen);
            int res = todigit(s_copy[0]);
            for(int i = 1;i < slen; i++)
            {
                if(todigit(s_copy[i - 1]) < todigit(s_copy[i]))
                {
                    res += todigit(s_copy[i]) - 2 * todigit(s_copy[i - 1]) ;
                }
                else
                {
                    res += todigit(s_copy[i]);
                }
            }
            return res;
        }
       
        int todigit(char ch) {     
            switch (ch) {
                case 'I':
                    return 1;
                case 'V':
                    return 5;
                case 'X':
                    return 10;
                case 'L':
                    return 50;
                case 'C':
                    return 100;
                case 'D':
                    return 500; 
                case 'M':
                    return 1000; 
           } 
          return 0; 
        }

    };

  • 相关阅读:
    Entity Framework Code-First(10.3):Property Mappings
    Entity Framework Code-First(10.2):Entity Mappings
    Entity Framework Code-First(10.1):EntityTypeConfiguration
    Entity Framework Code-First(10):Fluent API
    Entity Framework Code-First(9.11):DataAnnotations
    Entity Framework Code-First(9.10):DataAnnotations
    Entity Framework Code-First(9.9):DataAnnotations
    Entity Framework Code-First(9.8):DataAnnotations
    Entity Framework Code-First(9.7):DataAnnotations
    JAVA-初步认识-第六章-类与对象体现
  • 原文地址:https://www.cnblogs.com/CodingGirl121/p/5409364.html
Copyright © 2011-2022 走看看