Problem overview
The function burrrrp takes a number n and returns the sound of a burp: "bu", then n letters r, then "p". The number is between 1 and 20, and the result is all lowercase.
For n = 4 the result is "burrrrp". For n = 1 it is "burp", the shortest burp. For n = 7 it is "burrrrrrrp".
Approach
Only one part of the answer changes with the input: the run of r letters. The start, "bu", and the end, "p", are always the same. That suggests a template with a hole in the middle: format!("bu{}p", ...). The hole is filled with "r" repeated n times.
The repeat method of a string slice does exactly that: "r".repeat(4) gives the new String "rrrr". It takes its count as a usize, while the function receives n as an i32, so the count is converted with n as usize.
The middle part grows with n while the rest stays put:
Another way to get the same result is a loop that pushes one r at a time onto a growing String. It works, but it needs a mutable variable, a loop and a counter, while repeat expresses "this many copies" directly. Reaching for a method that already does the job keeps the function to one line.
It also helps to see what {} does. Each {} in a format! template is replaced by the text form of the matching argument, in order. With one {} and one argument there is nothing to line up: the string produced by repeat is dropped into the middle of bu and p.
n | "r".repeat(n as usize) | Result |
|---|---|---|
| 1 | r | burp |
| 2 | rr | burrp |
| 4 | rrrr | burrrrp |
| 10 | rrrrrrrrrr | burrrrrrrrrrp |
Step by step
- Build the middle. Write
"r".repeat(n as usize). Forn = 4it is"rrrr". - Put it in the template.
"bu{}p"has the fixed start, a{}for the middle and the fixed end. - Return the formatted string.
format!works likeprintln!, but returns aStringinstead of printing.
The solution in Rust
impl Solution {
fn burrrrp(n: i32) -> String {
return format!("bu{}p", "r".repeat(n as usize));
}
}
Some details worth knowing:
- Letters, not words. The template text
buandpsits right next to the{}, with no spaces. Any space inside the quotes would end up in the result. as usize. Rust won't pass ani32where ausizeis expected, so"r".repeat(n)doesn't compile. The cast is exact for 1 to 20. A negativenwould become a hugeusize, becauseasdoesn't check the sign.- An expression inside the arguments. The arguments of
format!can be any expressions, so the call torepeatgoes straight in. TheStringit returns is a temporary that lives until the formatting is done.
Edge cases and common mistakes
- Off-by-one in the count. Writing
(n + 1)or(n - 1)gives onertoo many or too few. Forn = 1, the correct middle is a singler. - Forgetting the cast. The compiler rejects the call and says it expected a
usizebut found ani32. - Using the character
'r'. Single quotes make achar, which has norepeatmethod. The method belongs to strings, so use"r". - Stray spaces.
"bu {} p"would put spaces in the burp.
Testing
n = 4gives"burrrrp".n = 1gives"burp".n = 7gives"burrrrrrrp".
