본문 바로가기
알고리즘/백준 알고리즘

[백준 알고리즘] 문제 4673번 : 셀프 넘버 (JAVA)

by Bhinney 2022. 8. 23.

문제 링크 : 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


1. 셀프 넘버를 찾자.

1️⃣ n이라는 정수를 파라미터로 받는 selfNum 함수를 만듦.

public static int selfNum(int n){}

2️⃣ sum의 초기값을 n으로 설정.

 : 셀프 넘버를 구하는 식을 살펴 보면, n값에 각 자리 수를 더하기 때문이다.

 (예 : d(15) = 15 + 1 + 5)

public static int selfNum(int n){
    int sum = n;
}

3️⃣ 셀프 넘버를 찾기 위한 반복문 설정

☝🏻 반복문의 조건이 0이 아닐 때인 이유 : 반복문 안에서 n을 계속 나누어 줄 것이기 때문.

✌🏻 n을 10으로 나눈 값을 더하는 이유 : 1의 자리 값을 더해주기 위해서

🤟🏻 n을 10으로 나누는 이유 : 다음 자리 수를 1의 자리 수로 가져와 반복문 안에서 더해주기 위해서.

public static int selfNum(int n){
    int sum = n;
    
    while(n != 0){
    	sum += n%10;
        n = n/10;
    }
    
    return sum;
}

<예시> 

n = 1234 라고 가정.

n % 10 = 1234 % 10 = 4 --> n의 1의 자리 수인 4를 구함

sum = 1234 + 4

n = 1234 / 10 = 123 --> 이렇게 나누어 1의 자리 수를 없애고, 다음 자리 수를 1의 자리수로 가져옴.

 

다시 반복문을 돌면 , 

sum = 1234 + 4

n % 10 = 123 % 10 = 3

sum = 1234 + 4 + 3

n = 123 / 10 = 12

 

이런 식으로 n이 0이 될 때까지 반복.


2. 리턴 받은 셀프 넘버를 Set에 추가하고 비교하자.

1️⃣ 셀프 넘버를 추가할 Set을 생성

import java.util.*;

public class Main{
    public static void main(String[] args){
    	Set<Integer> set = new HashSet<>();
    }
}

2️⃣ 셀프 넘버를 Set에 추가

: 10,000보다 큰 수는 필요가 없으므로, 10,000 이하인 셀프 넘버만 Set에 추가.

import java.util.*;

public class Main{
    public static void main(String[] args){
    	Set<Integer> set = new HashSet<>();
        
        for(int i = 1; i <= 10000; i++){
            int num = selfNum(i);
            
            if(num <= 10000){set.add(num);}
        }
    }
}

3️⃣ Set에 담긴 셀프 넘버가 아닌 수만 출력

import java.util.*;

public class Main{
    public static void main(String[] args){
    	Set<Integer> set = new HashSet<>();
        
        for(int i = 1; i <= 10000; i++){
            int num = selfNum(i);
            
            if(num <= 10000){set.add(num);}
        }
        
        for(int j = 1; j <= 10000; j++){
            if(!set.contains(j)){System.out.println(j);}
        }
    }
}

풀이

 

import java.util.*;

public class Main{
    public static void main(String[] args) {
    
        Set<Integer> set = new HashSet<>();

        for(int i =1; i <= 10000; i++){
        
            int num = selfNum(i);

            if(num <= 10000){set.add(num);}
        }

        for(int i =1; i <= 10000; i++){
        
            if(!set.contains(i)){ 
                System.out.println(i);
            }
        }
    }

    public static int selfNum(int n){

        int sum = n; 

        while(n != 0){ 
        
            sum += n%10;
            n = n/10;
        }

        return sum;
    }
}

댓글