Skip to content

Commit

Permalink
Create: 0013-roman-to-integer.rs / .ts
Browse files Browse the repository at this point in the history
  • Loading branch information
AkifhanIlgaz committed Jan 4, 2023
1 parent ee7a3bc commit f3f2e9c
Show file tree
Hide file tree
Showing 2 changed files with 70 additions and 0 deletions.
47 changes: 47 additions & 0 deletions rust/0013-roman-to-integer.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
impl Solution {
pub fn roman_to_int(s: String) -> i32 {
let s: Vec<char> = s.chars().collect();
let mut res = 0;

for i in 0..s.len() {
if i + 1 < s.len() && Self::get_value(s[i]) < Self::get_value(s[i + 1]) {
res -= Self::get_value(s[i]);
} else {
res += Self::get_value(s[i]);
}
}

res
}

pub fn get_value(ch: char) -> i32 {
match ch {
'I' => 1,
'V' => 5,
'X' => 10,
'L' => 50,
'C' => 100,
'D' => 500,
'M' => 1000,
_ => 0,
}
}

pub fn roman_to_int_functional(s: String) -> i32 {
s.chars().rfold(0, |acc, ch| {
acc + match ch {
'I' if acc >= 5 => -1,
'I' => 1,
'V' => 5,
'X' if acc >= 50 => -10,
'X' => 10,
'L' => 50,
'C' if acc >= 500 => -100,
'C' => 100,
'D' => 500,
'M' => 1000,
_ => 0,
}
})
}
}
23 changes: 23 additions & 0 deletions typescript/0013-roman-to-integer.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
function romanToInt(s: string): number {
let roman = {
I: 1,
V: 5,
X: 10,
L: 50,
C: 100,
D: 500,
M: 1000,
};

let result = 0;

for (let i = 0; i < s.length; i++) {
if (i + 1 < s.length && roman[s[i]] < roman[s[i + 1]]) {
result -= roman[s[i]];
} else {
result += roman[s[i]];
}
}

return result;
}

0 comments on commit f3f2e9c

Please sign in to comment.