Skip to content

Commit 1ef8ae6

Browse files
committed
2023-02-04 update: added "13. Roman to Integer"
1 parent a5298b5 commit 1ef8ae6

File tree

3 files changed

+39
-0
lines changed

3 files changed

+39
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,3 +16,4 @@ Profile on LeetCode: [fartem](https://leetcode.com/fartem/).
1616
|----------------------|----------------------------------------------------------|-------------------------------------------|
1717
| 1. Two Sum | [Link](https://leetcode.com/problems/two-sum/) | [Link](./lib/easy/two_sum.dart) |
1818
| 9. Palindrome Number | [Link](https://leetcode.com/problems/palindrome-number/) | [Link](./lib/easy/palindrome_number.dart) |
19+
| 13. Roman to Integer | [Link](https://leetcode.com/problems/roman-to-integer/) | [Link](./lib/easy/roman_to_integer.dart) |

lib/easy/roman_to_integer.dart

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
// https://leetcode.com/problems/roman-to-integer/
2+
class Solution {
3+
int romanToInt(String s) {
4+
final values = <String, int>{
5+
'I': 1,
6+
'V': 5,
7+
'X': 10,
8+
'L': 50,
9+
'C': 100,
10+
'D': 500,
11+
'M': 1000,
12+
};
13+
int result = 0;
14+
for (int i = s.length - 1; i >= 0; i--) {
15+
int curr = values[s[i]]!;
16+
if (curr * 4 < result) {
17+
result -= curr;
18+
} else {
19+
result += curr;
20+
}
21+
}
22+
return result;
23+
}
24+
}
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
import 'package:leetcode_dart/easy/roman_to_integer.dart';
2+
import 'package:test/test.dart';
3+
4+
void main() {
5+
group(
6+
'Example tests',
7+
() {
8+
final rti = Solution();
9+
test('3', () => expect(3, rti.romanToInt('III')));
10+
test('58', () => expect(3, rti.romanToInt('LVIII')));
11+
test('1994', () => expect(3, rti.romanToInt('MCMXCIV')));
12+
},
13+
);
14+
}

0 commit comments

Comments
 (0)