zoukankan      html  css  js  c++  java
  • LeetCode13 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 result = 0;
     5         for (int i = 0; i < s.size(); ++i) {
     6             if (s[i] == 'M') {
     7                 if (i - 1 >= 0 && s[i-1] == 'C') {
     8                     result += 800;
     9                 }
    10                 else {
    11                     result += 1000;
    12                 }
    13             }
    14             if (s[i] == 'D') {
    15                 if (i - 1 >= 0 && s[i-1] == 'C') {
    16                     result += 300;
    17                 }
    18                 else {
    19                     result += 500;
    20                 }
    21             }
    22             if (s[i] == 'C') {
    23                 if (i - 1 >= 0 && s[i-1] == 'X') {
    24                     result += 80;
    25                 }
    26                 else {
    27                     result += 100;
    28                 }
    29             }
    30             if (s[i] == 'L') {
    31                 if (i - 1 >= 0 && s[i-1] == 'X') {
    32                     result += 30;
    33                 }
    34                 else {
    35                     result += 50;
    36                 }
    37             }
    38             if (s[i] == 'X') {
    39                 if (i - 1 >= 0 && s[i-1] == 'I') {
    40                     result += 8;
    41                 }
    42                 else {
    43                     result += 10;
    44                 }
    45             }
    46             if (s[i] == 'V') {
    47                 if (i - 1 >= 0 && s[i-1] == 'I') {
    48                     result += 3;
    49                 }
    50                 else {
    51                     result += 5;
    52                 }
    53             }
    54             if (s[i] == 'I'){
    55                 result += 1;
    56             }
    57         }
    58         return result;
    59     }
    60 };
  • 相关阅读:
    【洛谷P1962】斐波那契数列
    【洛谷P3390】【模板】矩阵快速幂
    【洛谷P3070】[USACO13JAN]岛游记Island Travels
    【NOIp模拟赛】antipalindrome
    【洛谷P3930】SAC E#1
    【洛谷P3928】SAC E#1
    【洛谷P3927】SAC E#1
    【NOIp模拟赛】binary
    【NOIp模拟赛】value
    【洛谷P2341】[HAOI2006]受欢迎的牛
  • 原文地址:https://www.cnblogs.com/wangxiaobao/p/5751166.html
Copyright © 2011-2022 走看看