LeetCode 13. Roman to Integer -- 罗马数字转整数
2017-08-10 19:15
627 查看
Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
Status: Accepted
Runtime: 89 ms
Your runtime beats 93.16 % of java submissions.
Input is guaranteed to be within the range from 1 to 3999.
public class Main { //罗马数字表示法,基本字符有7个:I,V,X,L,C,D,M,分别表示1,5,10,50,100,500,1000。 public int romanToInt(String s) { int sum = 0; //先减去2倍,后面再遇到时每一位都是再加一次,所以还是减去了一次。相减的情况只有以下6种情况。 if (s.indexOf("IV") != -1) sum -= 2; if (s.indexOf("IX") != -1) sum -= 2; if (s.indexOf("XL") != -1) sum -= 20; if (s.indexOf("XC") != -1) sum -= 20; if (s.indexOf("CD") != -1) sum -= 200; if (s.indexOf("CM") != -1) sum -= 200; char[] c = s.toCharArray(); for (int i = 0; i < s.length(); i++) { if (c[i] == 'I') sum += 1; if (c[i] == 'V') sum += 5; if (c[i] == 'X') sum += 10; if (c[i] == 'L') sum += 50; if (c[i] == 'C') sum += 100; if (c[i] == 'D') sum += 500; if (c[i] == 'M') sum += 1000; } return sum; }//romanToInt public static void main(String[] args) { System.out.println(new Main().romanToInt("XXX"));//30 System.out.println(new Main().romanToInt("IVXX"));//24 System.out.println(new Main().romanToInt("IXXX"));//29 System.out.println(new Main().romanToInt("CDCXXI"));//521 } }3999 / 3999 test cases passed.
Status: Accepted
Runtime: 89 ms
Your runtime beats 93.16 % of java submissions.
相关文章推荐
- LeetCode 13. Roman to Integer 罗马数字转整数
- [LeetCode] 13. Roman to Integer 罗马数字转为整数
- LeetCode 13. Roman to Integer(罗马数字转阿拉伯数字)
- [LeetCode] Integer to Roman 整数转化成罗马数字
- LeetCode-13. Roman to Integer(罗马数字转阿拉伯数字)
- LeetCode | Integer to Roman(整数转换成罗马数字)
- [Leetcode] Roman to integer 罗马数字转成整数
- LeetCode 12 Integer to Roman (整数转罗马数字)
- [LeetCode] Roman to Integer 罗马数字转化成整数
- Leetcode 13 Roman to Integer 罗马数字转整数
- 13. Roman to Integer (整数转罗马数字)
- [LeetCode]12. Integer to Roman(整数转化为罗马数字)
- python解leetcode——13.Roman to Integer (罗马数字转为整数)
- LeetCode 13. Roman to Integer(阿拉伯数字转罗马字符)
- [C++]LeetCode 12: Integer to Roman(将整数转换为罗马数字)
- [LeetCode] Roman to Integer 罗马数字转整数
- leetcode:Integer to Roman(整数转化为罗马数字)
- (LeetCode) Roman to Integer --- 罗马数字转整数
- 【LeetCode-面试算法经典-Java实现】【013-Roman to Integer (罗马数字转成整数)】
- leetCode 12.Integer to Roman (整数转罗马数字) 解题思路和方法