ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 코딩 테스트를 위한 C++
    카테고리 없음 2023. 10. 2. 20:57

    String

    - 문자열 Parsing

    // substr(시작 index, 자를 개수)
    string output = B.substr(numEndIndexB, strEndIndexB - numEndIndexB);

    - 모두 소문자로 변경

    // 인자 : 기존 시작점, 기존 끝점, 변경될 시작점, 함수
    transform(A1.begin(), A1.end(), A1.begin(), ::tolower);

    - 문자열 -> 숫자 변경

    int A2I = stoi(A2);

    - 숫자 -> 문자열 변경

    string s2 = to_string(num);

    - 문자열 비교 규칙

    "9" > "12" // 앞자리를 비교
    "129" > "12" // 길이가 더 긴 쪽
    "0" > "-"
    "3" > "-9"
    "-9" > "-3" // 음수를 인식 X. 숫자 크기가 더 큰 쪽

    - 문자열들 조합으로 가장 큰 수 만들고 싶을 때

    bool comp (string a, string b) {
     return a + b > b + a // '30'과 '3'이 있다고 했을 때, 303보다 330이 더 크기 때문에
    }

    Queue

    typedef pair<int,int> point;
    
    Queue <point> q;
    
    q.push(make_pair(1, 1));
    
    cout >> q.front().first >> endl;
    cout >> q.front().second >> endl;
    
    q.pop();

    Sort

    - stable_sort
    : sort와 달리 정렬 기준 값이 동일 할 때, 기존 순서를 보장하는 sort

    ex. (3,a), (2,b), (2,c), (1,d)가 순서대로 존재하고 정수값으로 정렬할 때,
    (1,d), (2,b), (2,c), (3,a)의 결과를 내뱉지
    (1,d), (2,c), (2,b), (3,a)의 결과를 내뱉지 않음을 보장 (sort인 경우에는 보장하지 않음)

    // 인자 : 정렬할 자료구조의 시작, 정렬할 자료구조의 끝, (비교 함수)
    // 비교 함수는 선택 사항
    stable_sort(files.begin(), files.end(), cmp);

    문제풀이법

    - 최대공약수, 최소공배수

    • 최대공약수 (Greatest Common Divisor)
    •  
    int gcd(int a, int b) {
    	
        int mod = a % b;
        
        while (mod > 0) {
        	a = b;
            b = mod;
            mod = a % b;
        }
        return b;
    }
    • 최소공배수 (Least Common Multiple)
    int lcm(int a, int b) {
    	return a * b / gcd(a, b)
    }

    c++ 17 이상부터, #include<numeric>에 std::gcd, std::lcm 존재

Designed by Tistory.