From 631b562494d2957a78b97a9838cd0cba585d0b62 Mon Sep 17 00:00:00 2001 From: Spxg Date: Sun, 19 May 2024 11:25:53 +0800 Subject: [PATCH] Add problem 0326: Power of Three --- src/lib.rs | 1 + src/problem_0326_power_of_three/math.rs | 23 +++++++++++++++++++++++ src/problem_0326_power_of_three/mod.rs | 18 ++++++++++++++++++ 3 files changed, 42 insertions(+) create mode 100644 src/problem_0326_power_of_three/math.rs create mode 100644 src/problem_0326_power_of_three/mod.rs diff --git a/src/lib.rs b/src/lib.rs index fb15118..4c5220d 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -292,6 +292,7 @@ pub mod problem_0304_range_sum_query_2d_immutable; pub mod problem_0307_range_sum_query_mutable; pub mod problem_0316_remove_duplicate_letters; pub mod problem_0322_coin_change; +pub mod problem_0326_power_of_three; pub mod problem_0331_verify_preorder_serialization_of_a_binary_tree; pub mod problem_0338_counting_bits; pub mod problem_0341_flatten_nested_list_iterator; diff --git a/src/problem_0326_power_of_three/math.rs b/src/problem_0326_power_of_three/math.rs new file mode 100644 index 0000000..750935f --- /dev/null +++ b/src/problem_0326_power_of_three/math.rs @@ -0,0 +1,23 @@ +pub struct Solution; + +impl Solution { + pub fn is_power_of_three(n: i32) -> bool { + // 3^19 < i32::MAX + // 3^20 > i32::MAX + n > 0 && (1_162_261_467 % n == 0) + } +} + +impl super::Solution for Solution { + fn is_power_of_three(n: i32) -> bool { + Self::is_power_of_three(n) + } +} + +#[cfg(test)] +mod tests { + #[test] + fn test_solution() { + super::super::tests::run::(); + } +} diff --git a/src/problem_0326_power_of_three/mod.rs b/src/problem_0326_power_of_three/mod.rs new file mode 100644 index 0000000..ecc592d --- /dev/null +++ b/src/problem_0326_power_of_three/mod.rs @@ -0,0 +1,18 @@ +pub mod math; + +pub trait Solution { + fn is_power_of_three(n: i32) -> bool; +} + +#[cfg(test)] +mod tests { + use super::Solution; + + pub fn run() { + let test_cases = [(27, true), (0, false), (9, true), (45, false)]; + + for (n, expected) in test_cases { + assert_eq!(S::is_power_of_three(n), expected); + } + } +}