10872
재귀 단계
팩토리얼
- 숫자를 입력받으면 팩토리얼을 출력.
- 단, for문 사용하지 않고 재귀함수 사용
import java.util.Scanner;
public class bj10872_0122 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
System.out.println(fact(N));
}
static int fact(int N) {
if (N == 0) {
return N+1;
}
N = N * fact(N - 1);
return N;
}
}
- 재귀함수 자체가 오랜만이고 java로 쓰는 건 처음이라 생각보다 시간을 너무 많이 썼다... (앞 글에 올린 하노이보다 먼저 한 문제)
1065
함수 단계
한수
- 어떤 양의 정수 X의 각 자리가 등차수열을 이룬다면, 그 수를 한수라고 한다.
- N이 주어졌을 때, 1보다 크거나 같고 N보다 작거나 같은 한수의 개수를 출력.
- ex) 110 > 99, 210>105, 1000>144, 500>119
import java.util.Scanner;
public class bj1065_0122 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
sc.close();
int cnt = 0;
for (int i = 1; i <= N; i++) {
if (hTest(i) == true)
cnt++;
}
System.out.println(cnt);
}
static boolean hTest(int num) {
int len = lengthReturn(num);
if (len <= 2) {
return true;
} else if (len == 4) {
return false;
}
int[] arr = new int[3];
for (int i = 0; i < 3; i++) {
arr[i] = num / (int) Math.pow(10, 2 - i);
num = num - arr[i] * (int) Math.pow(10, 2 - i);
}
if ((arr[0] + arr[2]) % 2 == 0 && arr[1] == (arr[0] + arr[2]) / 2) {
return true;
}
return false;
}
static int lengthReturn(int num) {
int res = 0;
for (int i = 1; i <= 4; i++) {
if (num / (int) Math.pow(10, i) != 0) {
} else {
res = i;
break;
}
}
return res;
}
}
- 아 이거 생각보다 오래걸렸다..
- 그래도 함수를 사용해서 문제를 푸는 방법도 좀 익숙해진 것 같고, 계속 실수로 빼먹은 케이스때문에 한번에 성공 못한 적이 많은데 이건 한번에 성공해서 뿌듯했다...
'PS - BOJ' 카테고리의 다른 글
1138 - 한 줄로 서기, 1032 - 명령 프롬프트 (0) | 2022.01.23 |
---|---|
1124 - 언더프라임 (0) | 2022.01.23 |
11729 - 하노이 탑 이동 순서 (빠른 입출력!!) (0) | 2022.01.22 |
11653 - 소인수분해 (0) | 2022.01.22 |
8958 - OX퀴즈, 1712 - 손익분기점 (0) | 2022.01.22 |