Skip to content

Commit

Permalink
Add problem 1837: Sum of Digits in Base K
Browse files Browse the repository at this point in the history
  • Loading branch information
EFanZh committed Sep 13, 2023
1 parent 7ca52a5 commit f3ea4e5
Show file tree
Hide file tree
Showing 3 changed files with 55 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 @@ -1414,6 +1414,7 @@ pub mod problem_1824_minimum_sideway_jumps;
pub mod problem_1827_minimum_operations_to_make_the_array_increasing;
pub mod problem_1832_check_if_the_sentence_is_pangram;
pub mod problem_1833_maximum_ice_cream_bars;
pub mod problem_1837_sum_of_digits_in_base_k;

#[cfg(test)]
mod test_utilities;
36 changes: 36 additions & 0 deletions src/problem_1837_sum_of_digits_in_base_k/iterative.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
pub struct Solution;

// ------------------------------------------------------ snip ------------------------------------------------------ //

use std::num::NonZeroU8;

impl Solution {
pub fn sum_base(n: i32, k: i32) -> i32 {
let mut n = n as u8;
let k = NonZeroU8::new(k as _).unwrap();
let mut result = 0;

while n != 0 {
result += n % k;
n = n / k;
}

i32::from(result)
}
}

// ------------------------------------------------------ snip ------------------------------------------------------ //

impl super::Solution for Solution {
fn sum_base(n: i32, k: i32) -> i32 {
Self::sum_base(n, k)
}
}

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

pub trait Solution {
fn sum_base(n: i32, k: i32) -> i32;
}

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

pub fn run<S: Solution>() {
let test_cases = [((34, 6), 9), ((10, 10), 1)];

for ((n, k), expected) in test_cases {
assert_eq!(S::sum_base(n, k), expected);
}
}
}

0 comments on commit f3ea4e5

Please sign in to comment.