LeetCode Roman to Integer && Integer to Roman
来源:互联网 发布:鱼跃龙门网络歌手 编辑:程序博客网 时间:2024/04/28 07:17
Roman to Integer
:Given a roman numeral, convert it to an integer.Input is guaranteed to be within the range from 1 to 3999.题目大意是给你一个罗马数字让你转化为阿拉伯数字。不清楚罗马数
字请看维基百科的罗马数字的定义。这道题我是用map来做的,先将各个字母对应的
数字含义存到map里然后再通过遍历字符串来获得其数值。
代码:
class Solution {public: int romanToInt(string s) { map<char, int> transition;transition['I'] = 1;transition['V'] = 5;transition['X'] = 10;transition['L'] = 50;transition['C'] = 100;transition['D'] = 500;transition['M'] = 1000;map<char, int>::iterator iter;int result = 0;char last = s[0];char current = s[0];for(int i = 0; i < s.length(); i++){iter = transition.find(s[i]);if(iter != transition.end()){current = s[i];int lastValue = transition[last];int currentValue = transition[current];if(currentValue > lastValue)result = result + currentValue - 2 * lastValue;else result += currentValue;last = s[i];}}return result; }};
因为计算罗马数字的数值时需要看当前字母与前一个字母的大小才能决定是加还是减,所以这里定义了一个lastValue和一个currentValue。
Integer to Roman
:Given an integer, convert it to a roman numeral.Input is guaranteed to be within the range from 1 to 3999.这题刚好和上题相反,给你一个数让你转化为罗马数字。
这次用了一个转换表,根据这个字符串转换表来控制加入的字母。
代码:
class Solution {public:string transition;string returnResult(int times, int n){transition = "IVXLCDM"; string result;if(times < 4)result.append(times, transition[n]);else if(times == 4)result.append(1, transition[n]), result.append(1, transition[n + 1]);else if(times == 5)result.append(1, transition[n + 1]);else if(times >= 6 && times <= 8){result.append(1, transition[n + 1]);result.append(times - 5, transition[n]);}else {result.append(1, transition[n]);result.append(1, transition[n + 2]);}return result;} string intToRoman(int num) {transition = "IVXLCDM"; string result = "";int div = 1000;int index = 6;while(num != 0 && index >= 0){int tmp = num / div;if(tmp > 0)result += returnResult(tmp, index);num %= div;div /= 10;index -= 2;}return result; }};
0 0
- LeetCode Roman to Integer && Integer to Roman
- 【leetcode】Roman to Integer | Integer to Roman
- Leetcode - "Roman to Integer" & "Integer to Roman"
- LeetCode:Roman to Integer,Integer to Roman
- LeetCode Integer to Roman & Roman to Integer
- leetcode - roman to integer & integer to roman
- LeetCode:Roman to Integer
- LeetCode: Integer to Roman
- LeetCode: Roman to Integer
- LeetCode Integer to Roman
- LeetCode: Integer to Roman
- LeetCode : Roman to Integer
- [Leetcode] Roman to Integer
- [Leetcode] Integer to Roman
- Leetcode: Integer to Roman
- Leetcode: Roman to Integer
- LeetCode Integer to Roman
- 【leetcode】Roman to Integer
- HTML 中的meta元素小结
- 对Objective-C中Block的追探
- 06.C语言和设计模式(备忘录模式)
- 20140625
- Intellij IDEA创建Maven Web项目
- LeetCode Roman to Integer && Integer to Roman
- 技术人员的常用缩略语集锦
- Openkm6定制版新特性
- The project was not built since its build path is incomplete.
- 一些不错的开源Flex项目
- 07.C语言和设计模式(观察者模式)
- MCC(移动国家码)和 MNC(移动网络码)
- iphone图片拉伸的几种方法
- 捉虫记录:图像bug杂记25-26日