JAVA/Coding Test

[JAVA] 백준 4673 셀프 넘버_브루트포스

오늘도개발 2024. 2. 4. 18:30

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 문이 조금 더 직관적이어서 좋은것 같다.