프로그래머스 레벨 1 테스트

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include <string>
#include <vector>
#include <algorithm>
 
using namespace std;
 
class CMath
{
    public:
    int GCDFunc(int a, int b) //최대공약수
    {
        int Min = (a > b) ? a : b;
        int Answer = 1;
        for(int i = Answer ; i <= a ; i++)
        {
            if(a % i == 0 && b % i == 0)
                Answer = i;
        }
        return Answer;
    }
    int LCMFunc(int a, int b)  //최소공배수
    {
        return a * b / GCDFunc(a,b);
    }
};
 
vector<int> solution(int n, int m) {
    vector<int> answer;
    
    CMath c;
    answer.emplace_back(c.GCDFunc(n,m));
    answer.emplace_back(c.LCMFunc(n,m));
    
    return answer;
}
 

최소공배수: 공배수 중에서 가장 작은 수
   (最小公培數, [LCM] Least Common Multiple)

최대공약수: 공약수 중에서 가장 큰 수
   (最大公約數, [GCD] Greatest Common Divisor)

 

 

프로그래머스 레벨 1 테스트

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <vector>
#include <iostream>
 
using namespace std;
 
vector<int> solution(vector<int> arr) 
{
    vector<int> answer;
    
    int PrevNum = -1;
    for(int i = 0 ; i < arr.size() ; i++)
    {
        if(PrevNum == -1)
        {
            answer.emplace_back(arr[i]);
            PrevNum = arr[i];
        }   
        else
        {
            if(PrevNum != arr[i])
            {
                answer.emplace_back(arr[i]);
                PrevNum = arr[i];
            }
        }
    }
 
    return answer;
}
 

내가 만든 코드

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
 
vector<int> solution(vector<int> arr) 
{
 
    arr.erase(unique(arr.begin(), arr.end()),arr.end());
 
    vector<int> answer = arr;
    return answer;
}
 
 

모범 코드

alogorithm 라이브러리의 unique() 사용

unique() 함수 사용

-> 배열에서 연속으로 중복되는 내용을 쓰레기값으로 만든 후 배열의 맨끝으로 보내버리는 함수

unique() 함수 작동완료 시 반환값은 위치값으로, 맨 뒤로 보내진 쓰래기 배열의 첫번째로 이동한다.

레벨 1 테스트

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <string>
#include <vector>
 
using namespace std;
 
string solution(string s) {
    string answer = "";
    
    int strSize = s.length();
    
    if(strSize % 2 == 0// 짝수
    {
        answer += s.at((strSize / 2-1);
        answer += s.at(strSize / 2);
    }
    else
        answer = s.at(strSize / 2);
        
    
    
    return answer;
}
 

내가 푼것.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <string>
#include <vector>
 
using namespace std;
 
string solution(string s) 
{
   int strSize = s.length();
    
    if(strSize % 2 == 0// 짝수
        return s.substr((strSize * 0.5)-1 , 2); 
    else
        return s.substr(strSize * 0.5);
 
    return string();
}
 

모범 답안

string class의 substr을 사용한다.

substr(출력하고싶은 문자열 시작위치, 출력갯수);

+ Recent posts