Question:given a Roman numeral, convert it to an integer.
Input is guaranteed to being within the range from 1 to 3999.
Analysis: The problem is to convert the string of the Roman number entered into an integer. Method: Scanning the string from left to right, requires three variables: Temp records the segmented number, LASTV represents the number that has just been scanned, and CURV represents the number currently being scanned.
1. If Lastv = = curv, the record variable plus the current character;
2. If Lastv < CURV, the current character minus the record variable record value;
3. If Lastv > curv, record variables are added directly to the results.
Answer:
Public classSolution { Public intRomantoint (String s) {if(s = =NULL|| S.length () = = 0) return0; intsum = 0; inttemp = Chartoint (S.charat (0)); intLastv =temp; for(intI=1; I<s.length (); i++){ Charc =S.charat (i); intCURV =Chartoint (c); if(Lastv = =curv) Temp+=curv; Else if(Lastv <curv) {Temp= CURV-temp; } Else{sum+=temp; Temp=curv; } Lastv=curv; } Sum+=temp; returnsum; } Private intChartoint (Charc) {//TODO auto-generated Method Stub Switch(c) { Case' I ':return1; Case' V ':return5; Case' X ':return10; Case' L ':return50; Case' C ':return100; Case' D ':return500; Case' M ':return1000; default:return0; } }}
Leetcode--Roman to Integer