leetcode之旅(10)-Roman to Integer
2016-03-29 22:57
471 查看
题目描述:
Given a roman numeral, convert it to an integer. Input is guaranteed to be within the range from 1 to 3999. Subscribe to see which companies asked this question
预备知识:
记数方法
基本字符I
V
X
L
C
D
M
相应的阿拉伯数字表示为
1
5
10
50
100
500
1000
1、相同的数字连写,所表示的数等于这些数字相加得到的数,如:Ⅲ = 3;
2、小的数字在大的数字的右边,所表示的数等于这些数字相加得到的数, 如:Ⅷ = 8;Ⅻ = 12;
3、小的数字,(限于Ⅰ、X 和C)在大的数字的左边,所表示的数等于大数减小数得到的数,如:Ⅳ= 4;Ⅸ= 9;
4、正常使用时,连写的数字重复不得超过三次。(表盘上的四点钟“IIII”例外)
5、在一个数的上面画一条横线,表示这个数扩大1000倍。 ##
思路:
一个罗马字符对应一个数字权,那么就可以用数据结构map
对于s中出现的每一个罗马字符从右到左(无低位高位这么一说),如果权值在变大,则权相加
如果变小了,则减去这个权值 ##
代码:
import java.util.HashMap; import java.util.Map; public class Solution { public int romanToInt(String s) { int result=0; Map<Character,Integer> roman = new HashMap<Character,Integer>(); roman.put('I', 1); roman.put('V', 5); roman.put('X', 10); roman.put('L', 50); roman.put('C', 100); roman.put('D', 500); roman.put('M', 1000); for(int i=s.length()-1;i>=0;i--) { if(i==s.length()-1) { result=roman.get(s.charAt(i)); continue; } if(roman.get(s.charAt(i)) >= roman.get(s.charAt(i+1))) result+=roman.get(s.charAt(i)); else result-=roman.get(s.charAt(i)); } return result; } }
相关文章推荐
- leetcode之旅(10)-Roman to Integer
- 1013. 数素数 (20)
- --专访雷果国: 从1.5K到18K 一个程序员的5年成长之路--
- JDBC第四次学习
- 将网站部署到服务器上出现_STORAGE_WRITE_ERROR_问题
- 探索软件工程道路上的我 V (Θ∀Θ#)
- AS项目新建错误:cant resolve symbol R
- HDU 3038
- spring---one
- warning: function declared implicitly错误原因
- Raspberry安装ssh
- C#扫盲之:==/Equals /ReferenceEquals 异同的总结,相等性你真的知道吗?
- passport.js学习笔记
- asp.net用npoi读取ecxel数据到oracle表
- Visual Studio中的环境变量(以Visual Studio 2013为例)
- android 上传图片到服务器
- React Native for Android 发布独立的安装包
- C语言实现字节流与十六进制字符串的相互转换
- Android:Material系列:ActionBar-->Toolbar
- 机器人工具箱-6自由度机器人建模