Roman to Integer:轉換羅馬數字到阿拉伯數字
阿新 • • 發佈:2019-01-31
Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
解釋:羅馬數字:I:1
V:5
X:10
L:50
C:100
D:500
M:1000
比如:MCMLXX:1970
MDCLXVI:1666
思路:從高位到低位掃描
可將1970劃分為
[M] [CM] [L] [X] [X],即每個段內都是非降序,程式上體現為當出現升序時,減去前一個數字,否則加上前一個數字
class Solution { public int measure(char c){ if(c=='I'){ return 1; }else if(c=='V'){ return 5; }else if(c=='X'){ return 10; }else if(c=='L'){ return 50; }else if(c=='C'){ return 100; }else if(c=='D'){ return 500; }else if(c=='M'){ return 1000; } return 0; } public int romanToInt(String s) { int sum = 0; int pre = 0; int temp = 0; for(int i = 0;i <s.length() ;i++){ temp = measure(s.charAt(i)); if(temp <= pre){ sum += pre; pre = temp; }else{ sum -= pre; pre = temp; } } sum += pre; return sum; } }
最近做點簡單的題,偷偷懶......