Problem overview
The method Burrrrp receives a number n and returns the sound of a burp: "bu", then n letters r, then "p". For 4 the result is "burrrrp". For 1 it is "burp", the shortest burp. For 7 it is "burrrrrrrp". The result is always lower case.
Approach: two fixed pieces and a variable one
Look at what changes between the answers. The start "bu" and the end "p" are always the same. Only the number of r letters depends on n. So the answer is three pieces joined together, and only the middle piece needs to be computed.
For the middle piece, C# can build a string from one character repeated a number of times: new string('r', n). The character goes first, in single quotes because it is a char, and the count goes second.
Console.WriteLine(new string('r', 3));
Console.WriteLine("bu" + new string('r', 0) + "p");
rrr
bup
A count of 0 would give an empty middle, so the burp would lose its r letters. The lesson's n is at least 1, so that does not happen here.
Step by step
- Start the text. The literal
"bu"is a string, so the+that follows joins text. - Add the r letters.
new string('r', n)produces exactlynof them. Because it returns a string,+appends it as it is. - Close with the p. The literal
"p"goes last.
With n equal to 4 the pieces are "bu", "rrrr" and "p", which join into "burrrrp".
The solution in C#
class Solution {
public string Burrrrp(int n) {
return "bu" + new string('r', n) + "p";
}
}
The + operator is evaluated left to right, and every operand is a string, so each step produces a new string. Strings are immutable in C#, which means none of the pieces is ever modified: + builds a new string each time.
Single and double quotes are different things in C#. 'r' is a char, a single character. "r" is a string. The constructor needs the first, so new string("r", 3) does not compile: the compiler cannot convert a string to a char.
Edge cases and common mistakes
- Passing the arguments in the wrong order. The constructor takes the character first and the count second.
- Counting the letters. The count is the number of r letters, not the length of the whole word. For
n = 1the answer is"burp", with a single r. - A
charthat is added to anotherchar.'r' + 'r'would add two character codes and give a number. Here the r letters come fromnew string, so the problem does not arise. Acharadded to a string, as in"bu" + 'r', is appended as text. - Typing the letters by hand. A fixed string such as
"burrrrp"passes one test and fails the others, because the number of r letters depends onn.
It is worth checking the solution against the third example by hand. For n = 7 the middle piece is "rrrrrrr", seven letters, so the whole result is "bu", then those seven, then "p": "burrrrrrrp". The method never counts anything itself; the constructor does the counting, and the code stays the same for every n from 1 to 20.
Testing
| n | Result |
|---|---|
| 4 | "burrrrp" |
| 1 | "burp" |
| 7 | "burrrrrrrp" |
