Skip to content

Commit

Permalink
Add problem 0263: Ugly Number
Browse files Browse the repository at this point in the history
  • Loading branch information
Spxg committed May 25, 2024
1 parent 869fe85 commit 1a822c6
Show file tree
Hide file tree
Showing 3 changed files with 68 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -281,6 +281,7 @@ pub mod problem_0242_valid_anagram;
pub mod problem_0257_binary_tree_paths;
pub mod problem_0258_add_digits;
pub mod problem_0260_single_number_iii;
pub mod problem_0263_ugly_number;
pub mod problem_0268_missing_number;
pub mod problem_0274_h_index;
pub mod problem_0275_h_index_ii;
Expand Down
31 changes: 31 additions & 0 deletions src/problem_0263_ugly_number/iterative.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
pub struct Solution;

impl Solution {
pub fn is_ugly(n: i32) -> bool {
if n <= 0 {
return false;
}
let mut n = n;
let factors = [2, 3, 5];
for factor in factors {
while n % factor == 0 {
n /= factor;
}
}
n == 1
}
}

impl super::Solution for Solution {
fn is_ugly(num: i32) -> bool {
Self::is_ugly(num)
}
}

#[cfg(test)]
mod tests {
#[test]
fn test_solution() {
super::super::tests::run::<super::Solution>();
}
}
36 changes: 36 additions & 0 deletions src/problem_0263_ugly_number/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
pub mod iterative;

pub trait Solution {
fn is_ugly(num: i32) -> bool;
}

#[cfg(test)]
mod tests {
use super::Solution;

pub fn run<S: Solution>() {
let test_cases = [
(-2, false),
(-1, false),
(0, false),
(1, true),
(2, true),
(3, true),
(4, true),
(5, true),
(6, true),
(7, false),
(8, true),
(9, true),
(10, true),
(11, false),
(12, true),
(13, false),
(14, false),
];

for (num, expected) in test_cases {
assert_eq!(S::is_ugly(num), expected);
}
}
}

0 comments on commit 1a822c6

Please sign in to comment.