LeetCode - 13. Roman to Integer

简介: 13. Roman to Integer Problem's Link  ---------------------------------------------------------------------------- Mean:  给你一个字符串,代表罗马数字,将其转换为int型数字.

13. Roman to Integer

Problem's Link

 ----------------------------------------------------------------------------

Mean: 

给你一个字符串,代表罗马数字,将其转换为int型数字.

analyse:

Time complexity: O(N)

 

view code

/**
* -----------------------------------------------------------------
* Copyright (c) 2016 crazyacking.All rights reserved.
* -----------------------------------------------------------------
*       Author: crazyacking
*       Date  : 2016-02-16-12.06
*/
#include <queue>
#include <cstdio>
#include <set>
#include <string>
#include <stack>
#include <cmath>
#include <climits>
#include <map>
#include <cstdlib>
#include <iostream>
#include <vector>
#include <algorithm>
#include <cstring>
#include <bits/stdc++.h>
using namespace std;
typedef long long( LL);
typedef unsigned long long( ULL);
const double eps( 1e-8);

class Solution
{
public :
    int romanToInt( string s)
    {
        unordered_map < char , int > T =
        {
            { 'I' , 1   },
            { 'V' , 5   },
            { 'X' , 10   },
            { 'L' , 50   },
            { 'C' , 100 },
            { 'D' , 500 },
            { 'M' , 1000 }
        };

        int sum = T [s . back ()];
        for ( int i = s . length() - 2; i >= 0; -- i)
        {
            if ( T [s [ i ]] < T [s [ i + 1 ]])
                sum -= T [s [ i ]];
            else
                sum += T [s [ i ]];
        }
        return sum;
    }
};


int main()
{
    Solution solution;
    string s;
    while( cin >>s)
    {
        cout << solution . romanToInt(s) << endl;
    }
    return 0;
}

 

目录
相关文章
|
机器学习/深度学习
LeetCode 397. Integer Replacement
给定一个正整数 n,你可以做如下操作: 1. 如果 n 是偶数,则用 n / 2替换 n。 2. 如果 n 是奇数,则可以用 n + 1或n - 1替换 n。 n 变为 1 所需的最小替换次数是多少?
54 0
LeetCode 343. Integer Break
给定一个正整数 n,将其拆分为至少两个正整数的和,并使这些整数的乘积最大化。 返回你可以获得的最大乘积。
48 0
LeetCode 343. Integer Break
LeetCode之Reverse Integer
LeetCode之Reverse Integer
78 0
|
Java
[LeetCode] Roman to Integer 罗马数字转化成整数
链接:https://leetcode.com/problems/roman-to-integer/#/description难度:Easy题目:13. Roman to Integer Given a roman numeral, convert it to an integer.
765 0
|
Java 编译器
[LeetCode]Reverse Integer题解
题目链接:7. Reverse Integer 难度:Easy Reverse digits of an integer. Example1: x = 123, return 321 Example2: x = -123, return -321 N...
757 0
存储 算法 C语言
8 1
|
16天前
刷题之Leetcode160题(超级详细)
刷题之Leetcode160题(超级详细)
13 0

热门文章

最新文章