Problem overview
The function burrrrp receives a number n and returns the sound of a burp with n letters r: the text "bu", then n copies of r, then "p".
For n = 4 the answer is "burrrrp", the word in the lesson's title. For n = 1 it is "burp", and for n = 7 it is "burrrrrrrp". The number n goes from 1 to 20, and the result is all lower case.
Approach
Only the middle of the result changes. The beginning, "bu", and the end, "p", are the same for every input. So the function joins three pieces: a fixed start, a run of n letters r, and a fixed end.
The run of r letters is the interesting part. The std::string class can build a string of n equal characters in one expression, so no loop is needed.
It helps to see the three pieces for n = 4: "bu", "rrrr" and "p". Changing n changes only the middle piece, so the same expression works for every value from 1 to 20.
Step by step
- Start with
"bu". It is a string literal, the same for every call. - Build the r's.
string(n, 'r')creates a string withncopies of the character'r'. The count comes first, then the character in single quotes. - Finish with
"p"and return the joined result.
The solution in C++
class Solution {
public:
string burrrrp(int n) {
return "bu" + string(n, 'r') + "p";
}
};
Some C++ details about this line:
- The fill constructor.
string(4, 'r')is"rrrr". Putting that between"bu"and"p"gives"burrrrp". - Single and double quotes. The constructor takes a
char, so the letter is written'r'. A string literal such as"bu"uses double quotes. - Joining a literal to a string. The first
+has a string literal on its left and astd::stringon its right, which C++ allows, and it produces astd::string. The second+then joins that string and"p". Two literals next to each other with+, such as"bu" + "p", wouldn't compile. - The type of
n. The count is converted to an unsigned size. A negativenwould turn into an enormous count and fail with an exception. The lesson's values are between 1 and 20, so this never happens.
Edge cases and common mistakes
- Swapping the constructor's arguments.
string('r', n)compiles, but it builds'r'(code 114) copies of the character with coden, which is not what you want. Write the count first. - Using double quotes for the letter.
string(n, "r")doesn't match the fill constructor, because it expects a single character, not a string. - Counting the r's wrongly. The number
nis the number of r letters only. The u and p are extra. Withn = 1the answer is"burp", with exactly one r. - The smallest case. The code handles
n = 1as it is, and a count of 0 would give"bup", which the lesson never asks for. - Looping. A
forloop adding"r"ntimes also works. The one-line constructor is shorter and has fewer places for an off-by-one error.
Testing
n = 4gives"burrrrp".n = 1gives"burp".n = 7gives"burrrrrrrp".n = 20gives"burrrrrrrrrrrrrrrrrrrrp".
