problems: add previously solved problems
Signed-off-by: Matej Focko <mfocko@redhat.com>
This commit is contained in:
parent
3460ef6dbd
commit
96c6e8d66d
3 changed files with 67 additions and 0 deletions
42
problems/complex-number-multiplication.rs
Normal file
42
problems/complex-number-multiplication.rs
Normal file
|
@ -0,0 +1,42 @@
|
|||
use std::fmt;
|
||||
use std::str::FromStr;
|
||||
|
||||
#[derive(Debug, PartialEq)]
|
||||
struct Complex {
|
||||
real: i32,
|
||||
imag: i32,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct InvalidComplex;
|
||||
|
||||
impl FromStr for Complex {
|
||||
type Err = InvalidComplex;
|
||||
|
||||
fn from_str(input: &str) -> Result<Self, Self::Err> {
|
||||
let parts: Vec<&str> = input.split('+').collect();
|
||||
let real = parts[0].parse::<i32>().unwrap();
|
||||
let imag = parts[1].trim_end_matches('i').parse::<i32>().unwrap();
|
||||
|
||||
Ok(Complex { real, imag })
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for Complex {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
write!(f, "{}+{}i", self.real, self.imag)
|
||||
}
|
||||
}
|
||||
|
||||
impl Solution {
|
||||
pub fn complex_number_multiply(num1: String, num2: String) -> String {
|
||||
let left: Complex = num1.parse().unwrap();
|
||||
let right: Complex = num2.parse().unwrap();
|
||||
|
||||
(Complex {
|
||||
real: left.real * right.real - left.imag * right.imag,
|
||||
imag: left.real * right.imag + left.imag * right.real,
|
||||
})
|
||||
.to_string()
|
||||
}
|
||||
}
|
12
problems/contains-duplicate.swift
Normal file
12
problems/contains-duplicate.swift
Normal file
|
@ -0,0 +1,12 @@
|
|||
class Solution {
|
||||
func containsDuplicate(_ nums: [Int]) -> Bool {
|
||||
var encountered = Set<Int>()
|
||||
for x in nums {
|
||||
if encountered.contains(x) {
|
||||
return true
|
||||
}
|
||||
encountered.insert(x)
|
||||
}
|
||||
return false
|
||||
}
|
||||
}
|
13
problems/number-complement.swift
Normal file
13
problems/number-complement.swift
Normal file
|
@ -0,0 +1,13 @@
|
|||
class Solution {
|
||||
func findComplement(_ num: Int) -> Int {
|
||||
if num == 0 {
|
||||
return 0;
|
||||
}
|
||||
|
||||
if num & 1 != 0 {
|
||||
return findComplement(num >> 1) << 1;
|
||||
}
|
||||
|
||||
return (findComplement(num >> 1) << 1) + 1;
|
||||
}
|
||||
}
|
Loading…
Reference in a new issue