LeetCode OJ --问题与解答 Roman to Integer
来源:互联网 发布:酷狗音乐 mac 编辑:程序博客网 时间:2024/06/10 14:49
题目
Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
把罗马数字(String表示)变成整数
1 先查谷歌了解罗马数字的表示为何
2 确定后,马上想到HashMap可以用数字对应字符,然后一个个加起来。
3 难点是4和9 的部分,怎么处理。
4 可以看到只要字符代表的数 后面的比前面小,那么就要用后面的减去前面的。可是之前,我们每次都是做加法,所以这里就减两次前面的就可以了。
public class Solution { public int romanToInt(String s) { if(s.length()==0){ return 0; } HashMap<Character,Integer> record = new HashMap<Character,Integer>(); record.put('I',1); record.put('V',5); record.put('X',10); record.put('L',50); record.put('C',100); record.put('D',500); record.put('M',1000); char[] c = s.toCharArray(); int pre = record.get(c[0]); int ans = record.get(c[0]); for(int i= 1;i<c.length;i++){ int cur = record.get(c[i]); if(cur<=pre){ ans+=cur; } else{ ans=ans+cur-2*pre; } pre=cur; } return ans; }}
0 0
- LeetCode OJ --问题与解答 Roman to Integer
- 【LeetCode解答六】Integer to Roman问题Java解答
- 【LeetCode解答七】Roman to Integer问题Java解答
- LeetCode OJ:Roman to Integer
- LeetCode OJ:Integer to Roman
- LeetCode OJ - Roman to Integer
- LeetCode OJ - Integer to Roman
- [LeetCode OJ]Roman to Integer
- [LeetCode OJ]Integer to Roman
- LeetCode OJ : Roman to Integer
- LeetCode OJ Roman to Integer
- LeetCode OJ Integer to Roman
- LeetCode OJ - Integer to Roman
- LeetCode OJ - Roman to Integer
- <LeetCode OJ> 13 / 12 Roman to Integer & Integer to Roman
- LeetCode OJ 12 Integer to Roman
- LeetCode OJ 13 Roman To Integer
- LeetCode OJ: 12 Integer to Roman
- 如何用Qunit测试你的JavaScript代码
- iOS的CoreData用法
- 黑马程序员 交通灯管理系统
- 解决mini2440开发板和虚拟机相互ping不通
- XP系统停止服务,我们的自主操作系统去哪了
- LeetCode OJ --问题与解答 Roman to Integer
- Java实现的冒泡排序
- 在IOS程序中设置UIButton的字体大小
- Android4.2蓝牙Enable完全分析
- s3c6410开发板QT程序开机自动运行方法
- ends,flush,endl 用法区别
- git使用
- iOS7 icon 2
- 黑马程序员-java面向对象回顾