본문 바로가기

[Project Euler] Problem 036


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
public class P036 {
    public static void main(String args[]) {
      System.out.println(run());
    }
    
    public static String run() {
        int n = 1000000;
        int count = 0;
        
        do {
            if(isSymmetric(Integer.toString(n))
            && isSymmetric(Integer.toBinaryString(n))) {
                count += n;
            }
        } while(n-- > 0);
        
        return Integer.toString(count);
    }
    
    public static boolean isSymmetric(String s) {
        int idx = s.length() / 2;
 
        while(idx > 0) {
            if(s.charAt(idx - 1!= s.charAt(s.length() - idx--)) return false;
        }
 
        return true;
    }   
}
cs


11~14행:

10진수 정수  n 을 문자열과 이진수 문자열이 모두 대칭이면  count 에  n 을 더한다.

 Integer.toString() 과  Integer.toBinaryString() 은 주어진 int형 정수를 10진수 문자열, 2진수 문자열로 반환하는 메소드다.


20행:

주어진 문자열이 대칭인지 검사하는 메소드. 대칭이면 true, 아니면 false를 반환한다.


21행:

 idx 를 주어진 문자열 길이를 2로 나눈 몫으로 초기화한다.


23~25행:

 idx 가 1이 될 때까지 반복한다.

주어진 문자열 길이가 7이라면 인덱스는 0~6이므로


idx = 3;

s.charAt(3 - 1) != s.charAt(7 - 3) //s.charAt(2) != s.charAt(4);

idx--;


s.charAt(2 - 1) != s.charAt(7 - 2) //s.charAt(1) != s.charAt(5);

idx--;


s.charAt(1 - 1) != s.charAt(7 - 1) //s.charAt(0) != s.charAt(6);

idx--;


Since idx is zero break the loop


 str.charAt(int index)  메소드는 문자열의  index 번째 문자를 char 타입으로 반환하는 메소드다.


가운데 문자인  s.charAt(3) 을 제외하고 양쪽 문자를 비교해나가고, 두 문자가 다를 경우 비대칭 문자열이므로 false를 반환한다. 문자열 길이가 짝수일 때도 같은 원리로 진행된다.

'Programming > Solutions' 카테고리의 다른 글

[Project Euler] Coding Quiz 1  (0) 2021.01.12
[Project Euler] Problem 092  (0) 2021.01.11
[Project Euler] Problem 034  (0) 2021.01.11
[Project Euler] Problem 037  (0) 2019.07.25
[BAEKJOON] 2747번  (0) 2019.06.18