-
Notifications
You must be signed in to change notification settings - Fork 21
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add problem 1837: Sum of Digits in Base K
- Loading branch information
Showing
3 changed files
with
55 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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>(); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | ||
} | ||
} | ||
} |