Leetcode OJ 13 Roman to Integer [Easy]
来源:互联网 发布:soundtrack pro mac 编辑:程序博客网 时间:2024/05/19 09:48
题目描述:
Given a roman numeral, convert it to aninteger.
Input is guaranteed to be within the rangefrom 1 to 3999.
题目理解:
给定一个罗马数字(字符串的形式),将其转换成一个整数,范围是1到3999
分析:
1. 罗马数字1到10为:I,II,III,IV,V,VI,VII,VIII,IX,X
2. I(1),V(5),X(10),L(50),C(100),D(500),M(1000)
3. 观察“左减右加”的规律,左边的字符代表l的数子比紧挨的右边r小,则该l代表-l;繁殖如果l>=r,代表+l
4. 从字符串的末尾开始到启始位置遍历字符串,如果当前的字符代表的数字比上一个小,则result -= 当前字符代表的数字;如果当前字符代表的数字>=上一个,则result += 当前字符代表的数字
解答:
public int romanToInt(String s) { Map<Character, Integer> charToInt = new HashMap<Character,Integer>(); charToInt.put('I',1); charToInt.put('V',5); charToInt.put('X',10); charToInt.put('L',50); charToInt.put('C',100); charToInt.put('D',500); charToInt.put('M',1000); int result = 0; int pre = 0; int cur = 0; char[] nums = s.toCharArray(); for(int i = s.length() - 1; i >= 0; i--){ cur = charToInt.get(nums[i]); if(cur >= pre) result += cur; else result -= cur; pre = cur; } return result; }
阅读全文
0 0
- Leetcode OJ 13 Roman to Integer [Easy]
- [Leetcode 13, Easy] Roman To Integer
- 【LeetCode】(13)Roman to Integer(Easy)
- LeetCode #13 - Roman to Integer - Easy
- <LeetCode OJ> 13 / 12 Roman to Integer & Integer to Roman
- Leetcode[Easy] -- Roman to Integer
- LeetCode OJ 13 Roman To Integer
- LeetCode OJ-13-Roman to Integer
- 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
- mac mono 安装 command not found: mcs
- 链表面试题总汇
- QFileDialog使用对话框选取本地文件
- 39. Combination Sum
- Jexus部署Asp.Net Core项目
- Leetcode OJ 13 Roman to Integer [Easy]
- CSS3 Flex布局
- 一个数据库面试题,求更好解法
- package最佳实践
- poll函数
- 【转载】在windows中批量修改文件名
- Android Fragment切换动画的2种实现方式
- 最大似然估计
- CF