zoukankan      html  css  js  c++  java
  • Leetcode: 13.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.

    思路

    • 这个也没啥好说的吧,首先搞清楚罗马数字是个什么鬼?
    • 基本字符:I(1), V(5), X(10), L(50), C(100), D(500), M(1000)
    • 相同的数字连写、所表示的数等于这些数字相加得到的数、如:Ⅲ=3
    • 小的数字在大的数字的右边、所表示的数等于这些数字相加得到的数、如:Ⅷ=8、Ⅻ=12
    • 小的数字(限于 I、X 和C)在大的数字的左边、所表示的数等于大数减小数得到的数、如:Ⅳ=4、Ⅸ=9
    • 正常使用时、连写的数字重复不得超过三次
    • 在一个数的上面画一条横线、表示这个数扩大 1000 倍。

    代码

    class Solution {
    public:
        int romanToInt(string s) {
            int res = 0;
            int len = s.size();
            int i = 0;
            while(i < len){
                switch(s[i]){
                    case 'M' : 
                        res += 1000;
                        break;
                    case 'C':
                        if(i + 1 < len && (s[i + 1] == 'D' || s[i + 1] == 'M'))
                            res -= 100;
                        else res += 100;
                        break;
                    case 'D':
                        res += 500;
                        break;
                    case 'X':
                         if(i + 1 < len && (s[i + 1] == 'L' || s[i + 1] == 'C'))
                            res -= 10;
                        else res += 10;
                        break;
                    case 'L':
                        res += 50;
                        break;
                    case 'I':
                        if(i + 1 < len && (s[i + 1] == 'V' || s[i + 1] == 'X'))
                            res -= 1;
                        else res += 1;
                        break;
                    case 'V':
                        res += 5;
                        break;
                    default:
                        return 0;
                }
                i++;
            }
            
            return  res;
        }
    };
    
  • 相关阅读:
    Spring Boot 使用Redis
    openTSDB(转)
    httpClient 超时时间设置(转)
    HTTPClient 超时链接设置
    入坑python 自己写的小工具,纪念一下
    Linux下SVN创建新的项目
    java对象数组的概述和使用
    解决fastDFS客户端连接超时问题
    显示目录结构
    centos7开启80和8080端口
  • 原文地址:https://www.cnblogs.com/lengender-12/p/6816472.html
Copyright © 2011-2022 走看看