💡 조건문, 배열, 문자열, 정렬
(수수) : 숫자 주고, 한자리씩 읽어서, 숫자로 리턴하는 문제
#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;
}