13. Roman to Integer java solutions

Given a roman numeral, convert it to an integer.

Input is guaranteed to be within the range from 1 to 3999.

基本字符
I
V
X
L
C
D
M
相应的阿拉伯数字表示为
1
5
10
50
100
500
1000
  1. 相同的数字连写,所表示的数等于这些数字相加得到的数,如:Ⅲ = 3;
  2. 小的数字在大的数字的右边,所表示的数等于这些数字相加得到的数, 如:Ⅷ = 8;Ⅻ = 12;
  3. 小的数字,(限于Ⅰ、X 和C)在大的数字的左边,所表示的数等于大数减小数得到的数,如:Ⅳ= 4;Ⅸ= 9;
  4. 正常使用时,连写的数字重复不得超过三次。(表盘上的四点钟“IIII”例外)
  5. 在一个数的上面画一条横线,表示这个数扩大1000倍。

 

 1 public class Solution {
 2     public int romanToInt(String s) {
 3         if(s == null || s.length() == 0) return 0;
 4         char[] tmp = s.toCharArray();
 5         int ans = 0;
 6         for(int i = 0; i < tmp.length; i++){
 7             if(i < tmp.length-1 && getNum(tmp[i]) < getNum(tmp[i+1]))
 8                 ans -= getNum(tmp[i]);
 9             else
10                 ans += getNum(tmp[i]);
11         }
12         return ans;
13     }
14     
15     public int getNum(char ch){
16         if(ch == 'I')
17             return 1;
18         else if(ch == 'V')
19             return 5;
20         else if(ch == 'X')
21             return 10;
22         else if(ch == 'L')
23             return 50;
24         else if(ch == 'C')
25             return 100;
26         else if(ch == 'D')
27             return 500;
28         else
29             return 1000;
30     }
31 }

 

12. Integer to Roman java solutions

posted @ 2016-07-13 10:29  Miller1991  阅读(149)  评论(0编辑  收藏  举报