Today I had practiced the program roman to integer.
using the switch case to write the give roman and their corresponding integer value to it in a single for loop, if the number the less than the before number (-)otherwise (+).
class Solution {
public int romanToInt(String s) {
int ans = 0, num = 0;
for (int i = s.length() - 1; i >= 0; i--) {
switch (s.charAt(i)) {
case 'I':
num = 1;
break;
case 'V':
num = 5;
break;
case 'X':
num = 10;
break;
case 'L':
num = 50;
break;
case 'C':
num = 100;
break;
case 'D':
num = 500;
break;
case 'M':
num = 1000;
break;
}
if (4 * num < ans)
ans -= num;
else
ans += num;
}
return ans;
}
}
java
romantointeger
roman
leetcode13
leetcode
Top comments(0)
For further actions, you may consider blocking this person and/orreporting abuse