문제가 잘 안 보인다..
어떤 자연수에 대해 각 자릿수의 제곱의 합을 구하는 과정을 반복하면 어떤 수든 1이나 89로만 끝나게 되는데, 1천만 미만의 자연수 중에 89로 끝나는 수는 몇 개인지 구하는 문제다.
원래 풀려던 건 이거였다.
92번이 더 어렵다길래 한 번 봤더니 풀 수 있을 것 같아서 그냥 풀었다.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | public class P092 { public static void main(String args[]) { System.out.println(run()); } public static String run() { int n = 9999999; int count = 0; while(n > 0) { int temp = n--; int sum; do { sum = 0; while(temp > 0) { sum += ((temp%10)*(temp%10)); temp /= 10; } temp = sum; } while((sum != 1) && (sum != 89)); if(sum == 89) { ++count; } } return Integer.toString(count); } } | cs |
7행:
n 은 10000000 미만이므로 10000000 - 1 = 9999999로 초기화한다.
10행:
문제에서 '10000000 미만의 자연수 중에서'라는 조건이 주어졌으므로 9999999부터 1까지 반복한다.
23행:
자릿수 제곱의 합이 1 또는 89가 되면 반복문을 탈출한다.
(1도 아니고 89도 아닐 때만 조건이 참이므로 실행 흐름이 반복문 안에 있게 된다.)
14 ~ 15행:
sum 을 0으로 초기화하고,
17~20행:
temp 의 각 자릿수의 제곱을 sum 에 더한다.
22행:
다음 연산(자릿수 제곱의 합)에 쓰기 위해 temp 에 현재 결과 값인 sum 을 대입한다.
23행:
sum (현재 결과 값)이 1 또는 89면 반복문을 탈출한다.
25행:
결과 값이 89면 count 에 1을 더한다. 이 count 가 문제에서 요구하는 답이 된다.
34번 문제(https://t0pli.tistory.com/142)와 마찬가지로 문자열 변환을 통한 풀이도 가능할 것 같아서 해봤다.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | public class P092 { public static void main(String args[]) { System.out.println(run()); } public static String run() { int n = 9999999; int count = 0; while(n > 0) { String temp = Integer.toString(n--); do { int sum = 0; for(int i = 0; i < temp.length(); i++) { int a = temp.charAt(i) - '0'; sum += (a*a); } if(sum == 1) { break; } else if(sum == 89) { ++count; break; } else { temp = Integer.toString(sum); } } while(true); } return Integer.toString(count); } } | cs |
temp 에 문자열로 변환된 n 을 저장하고 그 문자열의 각 숫자 문자에 해당하는 정수 값을 구해 제곱한 후 sum 에 더해나간다.
if-else if-else 문 안 쓰고 stop 플래그를 쓰면 다음과 같다.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 | public class P092 { public static void main(String args[]) { System.out.println(run()); } public static String run() { int n = 9999999; int count = 0; while(n > 0) { String temp = Integer.toString(n--); boolean stop = false; do { int sum = 0; for(int i = 0; i < temp.length(); i++) { int a = temp.charAt(i) - '0'; sum += (a*a); } /* if(sum == 1) { break; } else if(sum == 89) { ++count; break; } else { temp = Integer.toString(sum); }*/ switch(sum) { case 89: ++count; case 1: stop = true; break; default: temp = Integer.toString(sum); } } while(!stop); } return Integer.toString(count); } } | cs |
34번 문제와 마찬가지로 유의미한 차이는 없는 것 같아서 그냥 다양하게 풀어본 것에 의미를 두기로 했다...
'Programming > Solutions' 카테고리의 다른 글
[Project Euler] Coding Quiz 4 (0) | 2021.01.15 |
---|---|
[Project Euler] Coding Quiz 1 (0) | 2021.01.12 |
[Project Euler] Problem 036 (0) | 2021.01.11 |
[Project Euler] Problem 034 (0) | 2021.01.11 |
[Project Euler] Problem 037 (0) | 2019.07.25 |