zoukankan      html  css  js  c++  java
  • LeetCode 13. Roman to Integer

    https://leetcode.com/problems/roman-to-integer/#/description

    Given a roman numeral, convert it to an integer.

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

    • 字符串简单题,要搞清楚转换规则。如果当前字母比前一个大,则相减,比如IV = 5 - 1;否则就相加,比如VI = 5 + 1,II = 1 + 1。
    • 罗马数字_百度百科
      • http://baike.baidu.com/link?url=JBuRWsGjAmYIlIhaPN_ywmIJBMrTWT6iKb2-WhqyTA6RqitOQuqnvQ2PHVfelAf00iGWWtgTzUjB3W4YMR0XWLfadA6YVi_s2J1aUgb-n1eBewvqGmyRpdH3VsVVs4q3
     1 #include <iostream>
     2 #include <string>
     3 using namespace std;
     4 
     5 class Solution {
     6 public:
     7     inline int map(const char inCh)
     8     {
     9         switch (inCh)
    10         {
    11             case 'I': return 1;
    12             case 'V': return 5;
    13             case 'X': return 10;
    14             case 'L': return 50;
    15             case 'C': return 100;
    16             case 'D': return 500;
    17             case 'M': return 1000;
    18             default:    return 0;
    19         }
    20         
    21     }
    22     
    23     int romanToInt(string s)
    24     {
    25         int result = 0;
    26         
    27         for (size_t i = 0; i < s.size(); i ++) {
    28             if ((i > 0) && (map(s[i]) > map(s[i - 1]))) {
    29                 result += map(s[i]) - 2 * map(s[i - 1]);
    30             } else {
    31                 result += map(s[i]);
    32             }
    33         }
    34         
    35         return result;
    36     }
    37 };
    38 
    39 int main ()
    40 {
    41     Solution testSolution;
    42     string sTest[] = {"XXI", "XXIX"};
    43 
    44     for (int i = 0; i < 2; i ++)
    45         cout << testSolution.romanToInt(sTest[i]) << endl;
    46     
    47     return 0;
    48 }
    View Code
  • 相关阅读:
    PCA
    Less
    Node.js的运行
    跨域
    Jquery中的Ajax
    JSON
    Ajax应用查询员工信息
    xampp中localhost与DreamWaver站点设置问题
    PHP
    HTTP是什么
  • 原文地址:https://www.cnblogs.com/pegasus923/p/7071745.html
Copyright © 2011-2022 走看看