zoukankan      html  css  js  c++  java
  • leetcode: Roman to Integer

    http://oj.leetcode.com/problems/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 class Solution {
     2 public:
     3     int romanToInt(string s) {
     4         int val = 0, mul = 0;
     5         char one, five, ten;
     6         const char *p = s.c_str();
     7         
     8         while (*p != '') {
     9             char ch = *p;
    10             
    11             if ('M' == ch) {
    12                 mul = 1000;
    13                 one = 'M';
    14                 five = '?';
    15                 ten = '?';
    16             }
    17             else if (('C' == ch) || ('D' == ch)) {
    18                 mul = 100;
    19                 one = 'C';
    20                 five = 'D';
    21                 ten = 'M';
    22             }
    23             else if (('X' == ch) || ('L' == ch)) {
    24                 mul = 10;
    25                 one = 'X';
    26                 five = 'L';
    27                 ten = 'C';
    28             }
    29             else {  // 'I' or 'V'.
    30                 mul = 1;
    31                 one = 'I';
    32                 five = 'V';
    33                 ten = 'X';
    34             }
    35             
    36             int tmp;
    37             
    38             if (one == ch) {
    39                 tmp = 1;
    40                 ++p;
    41                 while ((*p != '') && (one == *p)) {
    42                     ++tmp;
    43                     ++p;
    44                 }
    45                 
    46                 if (ten == *p) {
    47                     val += (mul * 9);
    48                     ++p;
    49                 }
    50                 else if (five == *p) {
    51                     val += (mul * 4);
    52                     ++p;
    53                 }
    54                 else {
    55                     val += (mul * tmp);
    56                 }
    57             }
    58             else if (five == ch) {
    59                 tmp = 5;
    60                 ++p;
    61                 while ((*p != '') && (one == *p)) {
    62                     ++tmp;
    63                     ++p;
    64                 }
    65                 
    66                 val += (mul * tmp);
    67             }
    68             // No need to handle ten, because it will be one in next level.
    69         }
    70         
    71         return val;
    72     }
    73 };
  • 相关阅读:
    表优化
    存储和压缩
    自定义函数
    Hadoop中SecondaryNameNode和HA(高可用)区别
    ASUS笔记本,更换了固态硬盘,重装系统前后开机都自动进入BIOS界面
    顶部下拉菜单制作笔记
    综合笔记
    工具sublime安装
    head引入样式
    滚动固定导航代码
  • 原文地址:https://www.cnblogs.com/panda_lin/p/roman_to_integer.html
Copyright © 2011-2022 走看看