본문 바로가기

Programming/알고리즘

[백준] 1110- 더하기 사이클 - JAVA[자바]

 

문제의 조건을 다시 한번 적어보자면, 

N의 1의 자릿수는 새로운 수의 10의 자리로,

N의 1의 자릿수와 10의 자릿수를 더한 값의 1의 자릿수는 새로운 수의 1의 자리로 가면 된다.

(만약 N 이 한 자릿수 정수라면 앞에 0을 붙여서 더한다.)

 

원래 숫자를 mother_num, 파생된 수를 son 이라고 하면, 

 

son의 십의 자리 숫자 : ((son % 10) * 10) 

son의 일의 자리 숫자:  ((son/10) + (son % 10)) % 10; 가 된다.

 

그래서 답을 적어보면 아래와 같다. 

 

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;

public class Main{
    public static void main(String[] args) throws IOException{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int mother_num = Integer.parseInt(br.readLine());
        int son = mother_num;
        int count = 0;
        
        son = ((son % 10) * 10) + (((son/10) + (son % 10)) % 10);
        count++;
     
        while (mother_num != son){
            son = ((son % 10) * 10) + (((son/10) + (son % 10)) % 10);
            count++;
        }        
        System.out.print(count);
    }
}

근데, 여기서 거슬리는게

똑같은 조건을 한번 바깥으로 빼 주어야 mother_num 과 son 이
처음 시작에 같게 되는 상황을 피할 수 있다.

 

같은 로직을 굳이 한번 바깥으로 빼지 않는 방법이 없을까?

 

 

=> 있다. Do-while으로 하면 된다.

Do-while을 사용하면 로직을 1회 시행 한 뒤에 조건을 비교할 수 있다.

 

 

do {
	son= ((son % 10) * 10) + (((son / 10) + (son % 10)) % 10);
	count++;
} while (mother_num != son);

 

 

위의 코드를 적용하면

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;

public class Main{
    public static void main(String[] args) throws IOException{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int mother_num = Integer.parseInt(br.readLine());
        int son = mother_num;
        int count = 0;
      
        do {
			son= ((son % 10) * 10) + (((son / 10) + (son % 10)) % 10);
			count++;
			} while (mother_num != son);
        System.out.print(count);
    }
}

위와같이 정리할 수 있다.