728x90
반응형
문자열 my_string과 정수 n이 매개변수로 주어질 때, my_string에 들어있는 각 문자를 n만큼 반복한 문자열을 return 하도록 solution 함수를 완성해보세요.
전에 프로그래머스의 어떤 문제를 풀었을 때 이런 답이 나와서 킹받았던 적이 있었는데 이런 문제가 등장할 거였으면 그 답변 또한 적어놓을껄.. 현재는 이중for문을 사용한 답밖에 생각나지 않았다.
#include <string>
#include <vector>
using namespace std;
string solution(string my_string, int n) {
string answer = "";
for(int i = 0; i < my_string.size(); i++){
for(int j = 0; j < n; j++){
answer.push_back(my_string[i]);
}
}
return answer;
}
n의 갯수만큼 배열의 원소가 반복적으로 출력되게 하고, 이걸 my_string 배열의 원소가 모두 출력되도록 해야했기에 현재의 식처럼 적었다.
<다른 사람의 풀이>
#include <string>
#include <vector>
using namespace std;
string solution(string my_string, int n) {
string answer = "";
for(const auto v : my_string)
{
answer += string(n,v);
}
return answer;
}
이제는 범위 연산자를 능숙하게 적용하고, 사용할 때이다!
#include <string>
#include <vector>
using namespace std;
string solution(string my_string, int n) {
string answer = "";
for(auto i : my_string)
for(int j = 0; j < n; j++)
answer += i;
return answer;
}
auto를 사용하는 방법 중에 참조자를 쓴 풀이도 있어 공유해본다
#include <string>
#include <vector>
using namespace std;
string solution(string my_string, int n) {
string answer = "";
for(auto& i: my_string) {
for(int j=0; j<n; j++) {
answer.push_back(i);
}
}
return answer;
}
728x90
반응형
'프로그래머스 C++ > Level.0' 카테고리의 다른 글
프로그래머스 Level.0 자릿수 더하기 (0) | 2023.08.11 |
---|---|
프로그래머스 Level.0 숨어있는 숫자의 덧셈 (1) (0) | 2023.08.02 |
프로그래머스 C++ Level. 0 제곱수 판별하기 (0) | 2023.07.04 |
프로그래머스 C++ Level. 0 편지 (0) | 2023.06.25 |
프로그래머스 C++ Level. 0 배열 자르기 (0) | 2023.04.27 |