Implemented problems 2,12,13

This commit is contained in:
Egor 2024-04-18 13:18:14 +03:00
parent 7fbad410b1
commit eb2ed30f46
4 changed files with 92 additions and 20 deletions

View file

@ -1,15 +1,35 @@
fn main() {
println!("{}", int_to_roman(1994));
}
// TODO: implement solution
pub fn int_to_roman(num: i32) -> String {
let roman_to_int = vec![
('M', 1000), ('D', 500), ('C', 100),
('L', 50), ('X', 10), ('V', 5), ('I', 1)
];
for i in 0..roman_to_int.len() {
let roman_nums = vec!['M', 'D', 'C', 'L', 'X', 'V', 'I'];
let mut result = String::with_capacity(15);
let (mut num, mut divisor) = (num, 1000);
for i in (0..roman_nums.len()).step_by(2) {
let roman = roman_nums[i];
let roman_amount = num / divisor;
match roman_amount {
0 => (),
1..=3 => {
for _ in 0..roman_amount { result.push(roman); }
},
5..=8 => {
let complement = roman_nums[i - 1];
result.push(complement);
for _ in 0..(roman_amount-5) { result.push(roman); }
},
4 | 9 => {
let complement_index = i - roman_amount as usize / 4;
let complement = roman_nums[complement_index];
result.push(roman);
result.push(complement);
},
_ => ()
}
return String::new();
num %= divisor;
divisor /= 10;
}
if result.is_empty() { result.push('0'); }
return result;
}

View file

@ -0,0 +1,13 @@
fn main() {
println!("{}", roman_to_int(String::from("MCMXCIV")));
}
pub fn roman_to_int(s: String) -> i32 {
s.chars().fold(0, |acc, c| {
let num = match c {
'M' => 1000, 'D' => 500, 'C' => 100, 'L' => 50,
'X' => 10, 'V' => 5, 'I' => 1, _ => 0
};
acc + num - 2 * (acc % num)
})
}

View file

@ -0,0 +1,16 @@
fn main() {
}
// TODO: imlpement
pub fn longest_common_prefix(strs: Vec<String>) -> String {
let mut result = String::with_capacity(200);
let index = 0;
loop {
let c = strs[0].as_bytes()[index];
for str in strs.iter() {
}
}
return result;
}

View file

@ -1,10 +1,33 @@
use std::ops::Deref;
fn main() {
}
// TODO: implement algorithm
pub fn add_two_numbers(l1: Option<Box<ListNode>>, l2: Option<Box<ListNode>>) -> Option<Box<ListNode>> {
return None;
let (mut l1, mut l2) = (l1, l2);
let mut head = Box::new(ListNode::new(0));
let mut tail = &mut head;
loop {
let mut sum = tail.val;
if let Some(node) = &l1 {
sum += node.val;
l1 = node.next.clone();
}
if let Some(node) = &l2 {
sum += node.val;
l2 = node.next.clone();
}
let next_node = Box::new(ListNode::new(sum / 10));
tail.val = sum % 10;
if l1.is_none() && l2.is_none() {
if next_node.val > 0 { tail.next = Some(next_node); }
break;
}
tail.next = Some(next_node);
tail = tail.next.as_mut().unwrap();
}
return Some(head);
}
// Definition for singly-linked list.