-
2331번: 반복수열
첫째 줄에 반복되는 부분을 제외했을 때, 수열에 남게 되는 수들의 개수를 출력한다.
www.acmicpc.net
시작 숫자가 주어지고 p의 값이 주어지면 숫자의 각 자릿수의 p제곱을 더한 값을 계속해 나가다가 보면 반복되는 구간이 발생한다.
이때 반복되는 구간을 제외한 수열의 개수를 구하면 된다.
ex) 45 -> (4*4+5*5) 41 -> (4*4+1*1) 41 -> 41 -> 41...
시작 숫자가 45이고 p의 값이 2일경우 정답은 1이다.
풀이
문제가 간단하다.
Collections에 계산되어 나온 값을 추가해 주고 만약 계산되어 나온 값이 Collections에 이미 존재한다면 해당
중복되어 나온 원소의 index가 곧 반복되지 않는 수열의 개수가 되기 때문에 중복되는 요소가 나올 때까지 반복문을 돌아주면 된다.
코드
import java.util.*; public class Main{ static int a; static int p; public static int cal(int n) { String str = Integer.toString(n); int returnValue = 0; for(int i =0;i<str.length();++i) { int x = 1; for(int t = 0;t<p;++t) { x = x*(str.charAt(i) - '0'); } returnValue += x; } return returnValue; } public static void main(String[] args) { Scanner sc = new Scanner(System.in); a = sc.nextInt(); p = sc.nextInt(); List<Integer>list = new ArrayList<>(); list.add(a); int x = cal(a); while(true) { if(list.contains(x)) { System.out.println(list.indexOf(x)); break; }else{ list.add(x); x = cal(x); } } } }