【Leetcode】Roman to Integer
来源:互联网 发布:2345看图王 mac 编辑:程序博客网 时间:2024/05/16 13:55
题目:
Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
解题思路:我们首先来明确一下罗马数字与阿拉伯数字的换算规则:如果当前数字比前一个大,说明这一段的值应该是当前这个值减去上一个值,比如IV = 5 – 1;否
则,将当前值加入到结果中,然后开始下一段记录,比如VI = 5 + 1, II=1+1。而罗马数字与阿拉伯数字对应变换是:I对应1,V对应5,X对应10,L对应50,C对应100,D对应500,M对应1000。因此,只需要从前往后读出字符,如果当前数字小于等于前一字符,则加上当前字符对应的数字;而当前数字更大时,减去前一个字符(要减去两倍,因为在前面扫描时已经加上过一次了,实际上不应该加,因此要多减一次)。
代码:
class Solution {public: inline int map(const char c){ switch(c){ case 'I': return 1; case 'V': return 5; case 'X': return 10; case 'L': return 50; case 'C': return 100; case 'D': return 500; case 'M': return 1000; default:return 0; } } int romanToInt(string s) { const size_t n=s.size(); int result=0; for(int i=0;i<n;i++){ if(i>0&&(map(s[i])>map(s[i-1]))){ result=result+map(s[i])-2*map(s[i-1]); }else{ result=result+map(s[i]); } } 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
- CSS z-index 属性
- 无插件Vim编程技巧
- VC6.0 显示代码行号
- Android4.1 屏蔽一些不用的apk桌面显示
- Hadoop NullPointerException
- 【Leetcode】Roman to Integer
- 正确使用Block避免Cycle Retain和Crash
- SlidingMenu属性详解
- 项目1(拓展)--矩形类
- 安装samba,出现perl(Convert::ASN1) is needed by samba……问题的解决方法
- 第五周项目一三角形类1
- android 在onCreate中获取空间宽高
- Redhat Linux telnet服务安装配置
- lighttpd 访问php 403 forbidden解决方案