본문 바로가기
작업/Problem Solving

백준 9815(Cabric Number Problem) 파이썬(python) 해결

문제

If we input a number formed by 4 digits and these digits are not all of one same value,

(4자리의 입력이면서 모두 같은 숫자가 아닐 경우 [ex. 1111, 2222])

 

 

then it obeys the following law. Let us operate the number in the following way:

(다음 방식의 순서 규칙을 따른다.)

 

 

ⓐ Arrange the digits in the way from bigger to smaller,

(4자리 숫자를 큰 수부터 작은 수로 배치하고,)

 

 

such that it forms the biggest number that could be made from these 4 digits;

(이를 바탕으로 가장 큰 수 4자리를 만든다.)

 

 

ⓑ Arrange the digits in the way from smaller to bigger,

(4자리 숫자를 작은 수부터 큰 수로 배치하고,)

 

 

such that it forms the smallest number that could be made from these 4 digits

(이를 바탕으로 가장 작은 수 4자리를 만든다.)

 

 

(If there is 0 among these 4 digits, the number obtained may be less than four digits);

(만약, 0이 포함된 4자리 수라면 만들어지는 가장 작은 수는 4자리보다 작을 수 있다.)

 

 

ⓒ Find the difference of these two numbers that is a new four digital number.

(만든 두 수의 차(뺄셈)로 새로운 수를 만든다.

 

 

Repeat the above process, we can finally always get the result 6174 or 0.

(위의 방식을 계속하면 최종적으로 6174나 0의 값이 나온다.) 

 

 

Please write the program to realize the above algorithm. 

(위의 방식을 프로그램으로 만든다.)

 

입력

Each case is a line of an integer. -1 denotes the end of input.

(각각의 케이스는 정수 입력으로 한다.  -1은 입력을 종료하는 의미이다.)

출력

If the integer is formed exactly by 4 digits and these digits are not all of one same value,

(정수가 정확히 4자리 수이며 그 수들이 모두 같은 값이 아니라면 [ex. 1111, 2222])

 

then output from the program should show the procedure for finding this number and the number of repetition times. Otherwise output "No!!".

(프로그램이 값을 찾는 과정과 처리 횟수를 출력한다. 규칙에 맞지 않는다면 "No!!"를 출력한다.)

 

 


Python3


'''
value_list = 테스트 케이스 리스트가 저장되는 배열

while문 = 테스트 케이스를 입력하는 구간
  -1을 입력했을 때, 사용자 입력이 종료되고 처리를 진행한다. 
  다른 값들은 모두 value_list에 저장한다.
'''

value_list = []

while(True):
    input_value = int(input())
    
    if (input_value == -1): break
    else:
        value_list.append(input_value)

'''
cnt = value_list에 저장된 값의 개수 저장

for문 = value_list에 저장된 값들을 문제에서 의도하는 대로 처리하는 구간
  N = 테스트 케이스 값 1개 저장
  cntN = 의도하는 값(6174 또는 0)이 나올 때까지의 반복 횟수 저장


 if문 = 테스트 케이스가 요구하는 형식이 아닐 경우 No!! 출력
  1. 4자리의 정수가 모두 같은 수일 경우 (1111, 2222, 3333)
  2. 4자리를 초과하는 정수일 경우 (12345, 223344)
  3. 4자리의 정수가 아닌 경우 (123, 234)
  
 else문 = 정상 테스트 케이스일 경우 처리
'''

cnt = len(value_list)

for i in range(cnt):
    N = value_list[i]
    cntN = 0
    print(f"N={N}:")
    if(N%1111 == 0 or N > 9999 or N < 1000):
        print("No!!")
    else:
        while(True):
            num1 = "".join(sorted(str(N))).lstrip("0")
            num2 = "".join(sorted(str(N), reverse=True))

            N = int(num2) - int(num1)

            print(f"{num2}-{num1}={N}")
            cntN += 1
            if (N==0 or N==6174):
                print(f"Ok!! {cntN} times")
                break
                
'''
while문 = 위의 else문에 포함된 구문
  문제에서 요구하는 출력 형식에 맞게 포맷팅하고, 결과를 도출하는 과정

 처리 과정에서 4자리 정수를 str()을 통해 문자열 리스트로 만든다.
 이를 각각 오름차순, 내림차순으로 정렬하는 sorted()를 사용한다.

 reverse=True는 내림차순 적용 (큰 수부터 작은 수로 배치)
 오름차순 배치 때, 0이 맨 앞자리에 나타날 수 있기 때문에 lstrip("0")으로 0값을 제거
'''

 

 

-끝-