Input is guaranteed to be within the range from 1 to 3999
s = "MDCC"=> 1700
s= "XXIV"=>24
s= ""XIX" => 19
s= "CM"=>900
I V X
1 5 10
X L C
10 50 100
C D M
100 500 1000
2. Implementation
Q1: check character and decide what value, what if something like IX
A1: whenever you are at unit 1,10,100 check to see if next are 5,10(for 1),50,100(for 10),,500,1000(for 100)
public int romanToInt(String s) { // validate the input if (s== null || s.length() == 0) return 0; s = s.trim(); if (s.length()==0) return 0; int res = 0; for (int i = 0 ; i < s.length(); i ++) { char c= s.charAt(i); switch(c) { case 'I': if ( i+1 < s.length() &&( s.charAt(i+1) == 'V' || s.charAt(i+1)=='X') ) { res-=1; } else res+=1; break; case 'X': if ( i+1 < s.length() &&( s.charAt(i+1)=='L' || s.charAt(i+1)=='C' ) ) res-=10; else res+= 10; break; case 'C': if ( i < s.length() -1 && (s.charAt(i+1)=='D' || s.charAt(i+1)=='M') ) { res -= 100; } else { res += 100; } break; case 'L': res += 50; break; case 'D': res += 500; break; case 'M': res += 1000; break; default: return 0; } } }3. Similar Ones (E) String to Integer (M) Integer to Roman (M) Integer to Number
No comments:
Post a Comment