码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode | Roman to Integer & Integer to Roman

时间:2014-09-22 23:17:03      阅读:195      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   io   ar   for   div   sp   on   

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         if (s.empty()) return 0;
 5         int dict[100];
 6         dict[I] = 1; dict[V] = 5; dict[X] = 10; dict[L] = 50;
 7         dict[C] = 100; dict[D] = 500; dict[M] = 1000;
 8     
 9         int ans = dict[s[0]];
10         for (int i = 1; i < s.length(); ++i) {
11             if (dict[s[i]] <= dict[s[i - 1]]) {
12                 ans += dict[s[i]];
13             } else {
14                 ans = ans - 2 * dict[s[i - 1]] + dict[s[i]];
15             }
16         }
17         return ans;
18     }
19 };

Integer to Roman

Given an integer, convert it to a roman numeral.

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

 1 class Solution {
 2 public:
 3     string intToRoman(int num) {
 4         string str[] = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"};
 5         int value[] = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};
 6         
 7         string ret = "";
 8         for (int i = 0; i < 13; ++i) {
 9             while (num >= value[i]) {
10                 ret += str[i];
11                 num -= value[i];
12             }
13         }
14         return ret;
15     }
16 };

 

Leetcode | Roman to Integer & Integer to Roman

标签:style   blog   color   io   ar   for   div   sp   on   

原文地址:http://www.cnblogs.com/linyx/p/3986686.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!