Leetcode OJ 13 Roman to Integer [Easy]
2017-06-22 21:22
253 查看
题目描述:
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 += 当前字符代表的数字
解答:
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; }
相关文章推荐
- leetcode_13_Roman to Integer(C++)(easy)
- LeetCode-13-Roman to Integer(number/模拟)-Easy
- Easy 4 Roman to Integer(13)
- leetcode_13_Roman to Integer (easy)
- LeetCode OJ 13 Roman To Integer
- LeetCode 13 Roman to Integer (easy)——python
- [Leetcode 13, Easy] Roman To Integer
- Easy 13题 Roman to Integer
- 【LeetCode】(13)Roman to Integer(Easy)
- LeetCode OJ - Integer to Roman
- 13 leetcode - Roman to Integer
- leetcode 13 roman to integer
- LeetCode | #13 Roman to Integer
- <LeetCode OJ> 13 / 12 Roman to Integer & Integer to Roman
- LeetCode OJ: 12 Integer to Roman
- LeetCode OJ --问题与解答 Roman to Integer
- leetcode 12 ,13 Integer to Roman &&Roman to Integer 罗马与阿拉伯数组转换
- leetcode-13:Roman to Integer
- leetcode——13——Roman to Integer
- leetcode13 :roman to integer