7월 6일 [2일차] 알고리즘 코딩 테스트(12번~30번)

마틴·2023년 7월 8일

📙 학습 문제

💡 조건문, 배열, 문자열, 정렬

  1. 배열의 평균값
  2. 배열 원소의 길이
  3. 배열 뒤집기
  4. 아이스 아메리카노
  5. 짝수 홀수 개수
  6. 문자열 뒤집기
  7. 모음 제거
  8. 편지
  9. 머쓱이보다 키 큰 사람
  10. 피자 나눠 먹기(1)
  11. 삼각형의 완성조건 (1)
  12. 순서쌍의 개수
  13. 중복된 숫자 개수
  14. 옷가게 할인 받기
  15. 점의 위치 구하기
  16. 특정 문자 제거하기
  17. 최댓값 만들기(1)
  18. 자릿수 더하기
    • 수수
  19. 중앙값 구하기

🏆 오늘의 미션


☢️ 풀이예시 - 먼저 풀어보고 나서 참고하기 🐸

  • 자릿수 더하기

    (수수) : 숫자 주고, 한자리씩 읽어서, 숫자로 리턴하는 문제

#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>

int solution(int n) {
    int answer = 0;
    for( ; n > 0 ; n /= 10) {  // 초기화 없이 그냥 십단위로 읽는다 (다만, 뒷자리부터 읽는다)
        answer += n % 10;  // 1의 자리수가 빠져 나온다.
    }
    return answer;
}
  • 시저 암호

    C로 제공되지 않은 문제라서 C++로 풀었습니다. (참고만 하세요)

#include <iostream>
#include <string>
#include <vector>

using namespace std;

string solution(string s, int n) {
    string answer = "";
    
    for(int i=0; i<s.length();i++){
        char c = s[i];
        if (c == ' ' ) 
            answer += ' ';
        else if ( c >= 'a' && c <= 'z') 
            answer += (c - 'a' + n) % 26 + 'a';
        else 
            answer += (c - 'A' + n) % 26 + 'A';
    }
    
    return answer;
}
  • 숫자 문자열과 영단어
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>

int solution(const char* s) {
    int answer = 0;
    char* ntoa[10] = { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"};
    int sLen = strlen(s);
    
    for(int i=0; i<sLen; i++) {
        if(s[i] >= '0' && s[i] <= '9') {
            answer = answer * 10 + (s[i] - '0');
        } else {
            for(int j=0; j<10; j++) {
                if(strncmp(ntoa[j], &s[i], 3) == 0) {
                    answer = answer * 10 + j;
                    break;
                }
            }
        }
    }
    
    return answer;
}
  • 삼각 달팽이
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>

int* solution(int n) {
	// return 값은 malloc 등 동적 할당을 사용해주세요. 할당 길이는 상황에 맞게 변경해주세요.
	int** matrix = (int**)calloc(n, sizeof(int*));
	for (int i = 0; i < n; i++) {
		matrix[i] = (int*)calloc(n, sizeof(int));
	}
	int* answer = (int*)calloc(n * (n + 1) / 2, sizeof(int));
	int length = n * (n + 1) / 2;
	int count = 1;
	int x = -1, y = 0;
	int direction = 0; // 0 아래로, 1 오른쪽으로, 2 위로

	for (int i = n; i > 0; i--) {
		for (int j = 0; j < i; j++) {
			if (direction == 0)
				matrix[++x][y] = count++;
			else if (direction == 1)
				matrix[x][++y] = count++;
			else
				matrix[--x][--y] = count++;
		}
		direction = (direction + 1) % 3;
	}

	count = 0;
	for (int i = 0; i < n; i++) {
		for (int j = 0; j < i + 1; j++) {
			answer[count++] = matrix[i][j];
		}
	}

	return answer;
}
profile
목원대 컴퓨터공학과

0개의 댓글