leetcode 13. Roman to Integer
2016-06-05 16:22
344 查看
Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
与leetcode 12题相反,将罗马数字转换成阿拉伯数字(小于3999)
从前向后遍历如果前面的比后面的小,则加上后面减去前面的值,指针向后移动一位,反之,加上前面的值.
public class A13RomantoInteger {
public int romanToInt(String s) {
int ans = 0;
for(int i = 0; i < s.length(); i++) {
int m = valueOfRoman(s.charAt(i));
if(i + 1 < s.length() && m < valueOfRoman(s.charAt(i + 1))) {
ans += valueOfRoman(s.charAt(i + 1)) - m;
i++;
} else {
ans += m;
}
}
return ans;
}
// I(1),V(5),X(10),L(50),C(100),D(500),M(1000)
public int valueOfRoman(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;
}
return 0;
}
}
Input is guaranteed to be within the range from 1 to 3999.
与leetcode 12题相反,将罗马数字转换成阿拉伯数字(小于3999)
从前向后遍历如果前面的比后面的小,则加上后面减去前面的值,指针向后移动一位,反之,加上前面的值.
public class A13RomantoInteger {
public int romanToInt(String s) {
int ans = 0;
for(int i = 0; i < s.length(); i++) {
int m = valueOfRoman(s.charAt(i));
if(i + 1 < s.length() && m < valueOfRoman(s.charAt(i + 1))) {
ans += valueOfRoman(s.charAt(i + 1)) - m;
i++;
} else {
ans += m;
}
}
return ans;
}
// I(1),V(5),X(10),L(50),C(100),D(500),M(1000)
public int valueOfRoman(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;
}
return 0;
}
}
相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- leetcode----Longest Substring Without Repeating Characters
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- leetcode_linearList
- leetcode_linearList02
- 021-Merge Two Sorted Lists(合并两个排好序的单链表);leetcode
- LeetCode[Day 1] Two Sum 题解
- LeetCode[Day 2] Median of Two Sorted Arrays 题解
- LeetCode[Day 3] Longest Substring Without... 题解
- LeetCode [Day 4] Add Two Numbers 题解