首页 > 其他 > 详细

Leetcode | Roman to Integer & Integer to Roman

时间:2014-09-22 21:34:54      阅读:215      评论:0      收藏:0      [点我收藏+]

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

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!