mo1lusca의 블로그
[백준] 25501 재귀의 귀재 - C 본문
https://www.acmicpc.net/problem/25501
isPalindrome 함수의 반환값과 recursion 함수의 호출횟수를 출력하면 되는 문제이다.
#include <stdio.h>
#include <string.h>
int cnt = 0;
int recursion(const char* s, int l, int r) {
cnt++;
if (l >= r) return 1;
else if (s[l] != s[r]) return 0;
else return recursion(s, l + 1, r - 1);
}
int isPalindrome(const char* s) {
return recursion(s, 0, strlen(s) - 1);
}
int main() {
int n;
scanf("%d", &n);
for (int i = 0; i < n; i++) {
cnt = 0;
char s[1000];
scanf("%s", s);
int temp = isPalindrome(s);
printf("%d %d\n", temp, cnt);
}
}
전역변수 cnt를 사용하여 recursion 함수의 호출 횟수를 세었다.
printf 함수에서 바로 isPalindrome을 호출하면 cnt가 isPalindrome보다 나중에 평가된다는 보장이 없으므로
printf 함수 전에 isPalindrome의 값을 temp에 넣어놓았다.
'PS' 카테고리의 다른 글
| [백준] 11729 하노이 탑 이동 순서 - C (0) | 2025.05.01 |
|---|---|
| [백준] 1003 피보나치 함수 - C (0) | 2025.05.01 |
| [백준] 2903 중앙 이동 알고리즘 - C (0) | 2025.04.14 |
| [백준] 1316 그룹 단어 체커 - C (1) | 2025.04.14 |
| [백준] 2941 크로아티아 알파벳 - C (0) | 2025.04.12 |