Skip to content

Commit

Permalink
Add problem 0326: Power of Three
Browse files Browse the repository at this point in the history
  • Loading branch information
Spxg committed May 19, 2024
1 parent 224fe29 commit 631b562
Show file tree
Hide file tree
Showing 3 changed files with 42 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 @@ -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;
Expand Down
23 changes: 23 additions & 0 deletions src/problem_0326_power_of_three/math.rs
Original file line number Diff line number Diff line change
@@ -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::<super::Solution>();
}
}
18 changes: 18 additions & 0 deletions src/problem_0326_power_of_three/mod.rs
Original file line number Diff line number Diff line change
@@ -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<S: Solution>() {
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);
}
}
}

0 comments on commit 631b562

Please sign in to comment.