https://www.acmicpc.net/problem/4673
4673번: 셀프 넘버
셀프 넘버는 1949년 인도 수학자 D.R. Kaprekar가 이름 붙였다. 양의 정수 n에 대해서 d(n)을 n과 n의 각 자리수를 더하는 함수라고 정의하자. 예를 들어, d(75) = 75+7+5 = 87이다. 양의 정수 n이 주어졌을 때,
www.acmicpc.net
접근 :
- 자기 자신과 각자리 수를 합하는 d(n) 메서드를 정의한다.
- 지정된 범위 내 생성자 숫자들을 작성한다.
- 범위 내 숫자들을 검사하여 생성자 여부를 확인 후 출력한다.
코드구현 :
public class SelfNumber {
static class Prac {
int n;
boolean[] selected;
private StringBuilder sb = new StringBuilder();
public Prac(int n) {
this.n = n;
this.selected = new boolean[n + 1];
}
public void cal_res(int temp, int res) {
res += temp % 10;
// 최고 높은 자릿수 인 경우
if (temp == 0) {
if (res > this.n) return;
this.selected[res] = true;
return;
}
cal_res(temp / 10, res);
}
// m개를 뽑는 메서드
public void rec_func() {
// 생성자 생성
for (int i = 1; i <= this.n; i++) {
cal_res(i, i);
}
// self 넘버 출력
for (int j = 1; j <= this.n; j++) {
if (!this.selected[j])
sb.append(j).append("\n");
}
}
public String print() {
return sb.toString();
}
}
public static void main(String[] args) {
Prac p = new Prac(10000);
p.rec_func();
System.out.println(p.print());
}
}
* 연습을 위해 재귀함수를 사용하였지만 while 문이 조금 더 직관적이어서 좋은것 같다.
'JAVA > Coding Test' 카테고리의 다른 글
[JAVA] 백준 1182 부분수열의 합_브루트포스 (0) | 2024.05.18 |
---|---|
[JAVA] 백준 14888 연산자 끼워넣기_브루트포스 (0) | 2024.05.18 |
[JAVA] 백준 7785 회사에 있는 사람_집합과 맵 (0) | 2023.04.17 |
[JAVA] 백준 14215 세 막대_기하: 직사각형과 삼각형 (0) | 2023.04.13 |
[JAVA] 백준 2903 중앙 이동 알고리즘_일반 수학1 (0) | 2023.04.13 |