Palindrome이란 앞에서부터 읽거나 뒤에서부터 읽으나 동일한 대칭 구조의 단어나 구를 말한다. 예를 들어
‘madam’, ‘level’, ‘aka’와 같은 것이 palindrome이다. 문자열을 입력하여 Palindrome 인지 판단하는
recursive program 을 작성하라.
단계 1. 본인의 학부, 학번, 이름을 출력한다.(따로 생략가능)
단계 2. scanf_s 로 “%s” 를 이용하여 문자열 을 입력 받는다. 문자열이 #이면 실행을 종료한다.
문자열은 알파벳 소문자만을 포함하며, 문자열의 길이는 20보다 작거나 같다.
단계 3. 문자열의 길이를 출력한다.
#include <string.h> 과 strlen( ) 함수를 사용하여 string의 길이를 구할 수 있다.
단계 4. 문자열이 palindrome이면 ‘yes’, 아니면 ‘no’를 출력한다.
단계 5. 단계 2로 돌아간다.
예제
Ex1
컴퓨터학부 201920394 홍길동
(scanf_s) abbd
4
No
(scanf_s) abba
4
Yes
(scanf_s) #
Ex2
컴퓨터학부 201920394 홍길동
(scanf_s) cakekac
7
Yes
(scanf_s)abcddcba
8
Yes
(scanf_s) #
문제 풀이
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int Palindrome(char* str) {
int i;
int strLen;
int truth = 1;
strLen = strlen(str);
for (i = 0; i < strLen / 2; i++) {
if (str[i] != str[strLen - 1 - i]) {
truth = 0;
break;
}
}
return truth;
}
int main() {
printf("2019115615 김규회\n");
char N[256];
while (true) {
scanf_s("%s", &N, sizeof(N));
if (strlen(N) > 20) {
return 0;
}
if (int(N[0]) == 35) {
printf("프로그램을 종료합니다.");
break;
}
for (int i = 0; i < strlen(N); i++) {
if (N[i] < 97 || N[i]>122) {
return 0;
}
}
if (Palindrome(N) == 1) {
printf("%d\n", strlen(N));
printf("Yes\n");
}
else {
printf("%d\n", strlen(N));
printf("No\n");
}
}
return 0;
}
주의해야 할 점 : 예외 상황 발생시 break와 return을 활용해주는것이 포인트인거 같다. 딱히 주의할 점은 없는거 같다.
풀이 결과
Recursion 을 이용하여 정수 N 의 binary representation 에 속한 ‘1’의 개수를 화면에 출력하라. N 의
binary representation 에 존재하는 ‘1’의 개수는, N 이 홀수인 경우에는 [N/2]의 binary
representation 에 있는 ‘1’의 개수 + 1 이다. 만약 N 이 짝수이면, [N/2]의 binary representation 에 있는
‘1’의 개수와 같다. 정수 N ( 1 ≤ N ≤ 1024)은 scanf_s 로 반복하여 입력 되도록 하고, N 이 -1 이면
수행을 종료한다.
예제
Ex1
컴퓨터학부 201920394 홍길동
(scanf_s) 16
1
(scanf_s) 17
2
(scanf_s) 18
3
(scanf_s) -1
Ex2
컴퓨터학부 201920394 홍길동
(scanf_s) 1024
1
(scanf_s) 128
1
(scanf_s) 1
1
(scanf_s) -1
문제 풀이
#include <stdio.h>
#include <stdlib.h>
int count = 0;
void binary(int n) {
if (n < 2) {
if (n == 1) {
count++;
}
}
else {
binary(n / 2);
if (n % 2 == 1) {
count++;
}
}
}
int main() {
int N;
while (true) {
count = 0;
scanf_s("%d", &N, sizeof(N));
if (N == -1) {
break;
}
binary(N);
printf("%d\n", count);
}
}
주의 해야 할 점 : 2진법에서 1의 개수를 구하는 것이므로 2진법 재귀함수 구하는 식에서 printf대신에 count ++해주면 쉽게 구할 수 있다.
풀이 결과