-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathroman-to-integer.cpp
67 lines (63 loc) · 1.9 KB
/
roman-to-integer.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
//
// Created by kobi on 12/26/21.
//
#include "roman-to-integer.hpp"
namespace leetcode_roman_to_integer {
template <char first, char second>
unsigned int get_special(const char c,
unsigned int def,
unsigned int val_first,
unsigned int val_second,
size_t& idx) {
unsigned int result{};
switch(c) {
default:
result+=def;
break;
case first:
result += val_first;
++idx;
break;
case second:
result += val_second;
++idx;
break;
}
return result;
}
unsigned int get_number(const std::string_view s) {
unsigned int result{};
if (s.empty()) {
return result;
}
for (size_t idx{}; s[idx]; ++idx) {
const auto c = s[idx];
switch (c) {
default:
return 0; // per leetcode description, should not happen. we can throw...
case 'I':
result += get_special<'V', 'X'>(s[idx+1], 1, 4, 9, idx);
break;
case 'V':
result+=5;
break;
case 'X':
result += get_special<'L', 'C'>(s[idx+1], 10, 40, 90, idx);
break;
case 'L':
result += 50;
break;
case 'C':
result += get_special<'D', 'M'>(s[idx+1], 100, 400, 900, idx);
break;
case 'D':
result += 500;
break;
case 'M':
result += 1000;
break;
}
}
return result;
}
}