백준
[ 백준 ] [ JAVA ] 1110 더하기 사이클
verlnn
2023. 5. 30. 00:43
반응형
https://www.acmicpc.net/problem/1110
1110번: 더하기 사이클
0보다 크거나 같고, 99보다 작거나 같은 정수가 주어질 때 다음과 같은 연산을 할 수 있다. 먼저 주어진 수가 10보다 작다면 앞에 0을 붙여 두 자리 수로 만들고, 각 자리의 숫자를 더한다. 그 다음,
www.acmicpc.net
브론즈부터 차근차근 풀어보려고 한다.
우선
- ( 조건부 )주어진 수가 10보다 작을 때, 앞에 0을 붙여서 두 자리 수로 만든다. Ex) 1 -> 01; 8 -> 08;
- 각 자리의 숫자를 더한다. Ex) 16 -> 1 + 6 = 7; 42 -> 4 + 2 = 6;
- 주어진 수의 가장 오른쪽 자리 수 + 앞에서 구한 결과의 가장 오른쪽 자리 수 Ex) 16 -> [ 6 ] + 2번[ 7 ] = 67;
해당 작업을 초기에 입력 받은 숫자와 3번의 결과가 같을 때 까지 반복시키고, 반복 횟수를 출력하면 된다.
위에 과정을 코드로 정리하면 아래와 같다.
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String n = sc.next();
String firstIndex;
String lastIndex;
String newInt = n;
int count = 0;
do {
if (Integer.parseInt(newInt) < 10) newInt = "0" + newInt;
firstIndex = getFirstIndex(newInt);
lastIndex = getLastIndex(newInt);
int firstCal = Integer.parseInt(firstIndex) + Integer.parseInt(lastIndex);
newInt = lastIndex + getLastIndex(String.valueOf(firstCal));
if (getFirstIndex(newInt).equals("0")) newInt = String.valueOf(Integer.parseInt(newInt));
count++;
} while (!n.equals(newInt));
System.out.println(count);
}
private static String getFirstIndex(String target) {
return target.substring(0, 1);
}
private static String getLastIndex(String target) {
int length = target.length();
return target.substring(length - 1, length);
}
}
반응형