Skip to content

Commit

Permalink
add license_key_formatting
Browse files Browse the repository at this point in the history
  • Loading branch information
phinnl committed May 15, 2024
1 parent c3ada08 commit 353f84d
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 1 deletion.
3 changes: 2 additions & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,4 +28,5 @@ pub mod remove_duplicates_from_sorted_array;
pub mod add_strings;
pub mod flip_and_invert_image;
pub mod leaf_similar;
pub mod sum_of_left_leaves;
pub mod sum_of_left_leaves;
pub mod license_key_formatting;
29 changes: 29 additions & 0 deletions src/license_key_formatting.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
pub fn license_key_formatting(s: String, k: i32) -> String {
let s = s.to_uppercase().replace('-', "");
let mut result = String::new();
let mut cur = s.as_str();
while !cur.is_empty() {
let (chunk, rest) =
cur.split_at(std::cmp::max(0, cur.len() as isize - k as isize) as usize);
if result.is_empty() {
rest.clone_into(&mut result);
} else {
result = format!("{}-{}", rest, result);
}
cur = chunk;
}
result
}

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

#[test]
fn example_1() {
assert_eq!(
license_key_formatting("5F3Z-2e-9-w".to_owned(), 4),
"5F3Z-2E9W"
);
}
}

0 comments on commit 353f84d

Please sign in to comment.