|
| 1 | +```java |
| 2 | +import java.io.*; |
| 3 | +import java.util.*; |
| 4 | +import java.math.BigInteger; |
| 5 | + |
| 6 | +public class Main { |
| 7 | + public static void main(String[] args) throws IOException { |
| 8 | + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); |
| 9 | + StringBuilder input = new StringBuilder(br.readLine()); |
| 10 | + int n = input.length(); |
| 11 | + |
| 12 | + // target은 input + 1부터 시작한다. |
| 13 | + BigInteger addOne = new BigInteger(input.toString()).add(BigInteger.ONE); |
| 14 | + StringBuilder target = new StringBuilder(addOne.toString()); |
| 15 | + |
| 16 | + // 팰린드롬 만들기 |
| 17 | + makePalindrome(target); |
| 18 | + |
| 19 | + // input보다 큰 팰린드롬이 만들어지지 않은 경우 |
| 20 | + // mid를 기준으로 앞부분을 자르고, +1을 수행해 앞부분을 증가시켜본다. |
| 21 | + BigInteger inputBigInt = new BigInteger(String.valueOf(input)); |
| 22 | + BigInteger targetBigInt = new BigInteger(String.valueOf(target)); |
| 23 | + if (inputBigInt.compareTo(targetBigInt) >= 0) { |
| 24 | + int mid; |
| 25 | + if (n % 2 == 0) { |
| 26 | + mid = n/2; |
| 27 | + } else { |
| 28 | + mid = n/2 + 1; |
| 29 | + } |
| 30 | + |
| 31 | + String head = target.substring(0, mid); |
| 32 | + String newHead = new BigInteger(head).add(BigInteger.ONE).toString(); |
| 33 | + |
| 34 | + for (int i = 0; i < mid; i++) { |
| 35 | + target.setCharAt(i, newHead.charAt(i)); |
| 36 | + } |
| 37 | + // newHead가 head보다 길어질 수 있음. (ex. 99 -> 101) |
| 38 | + if (newHead.length() != head.length()) { |
| 39 | + target = new StringBuilder(head.substring(0, 1)).append(target); |
| 40 | + } |
| 41 | + // 앞부분을 증가시킨 target으로 다시 팰린드롬을 만든다. |
| 42 | + makePalindrome(target); |
| 43 | + } |
| 44 | + System.out.println(target.toString()); |
| 45 | + br.close(); |
| 46 | + } |
| 47 | + |
| 48 | + private static void makePalindrome(StringBuilder target) { |
| 49 | + int n = target.length(); |
| 50 | + int mid; |
| 51 | + if (n % 2 == 0) { |
| 52 | + mid = n/2; |
| 53 | + } else { |
| 54 | + mid = n/2 + 1; |
| 55 | + } |
| 56 | + // mid를 기준으로 뒤에 있는 숫자들을 앞에 있는 숫자들에 맞춘다. |
| 57 | + for ( int i = 0; i < mid ; i++ ) { |
| 58 | + if (target.charAt(i) == target.charAt(n-1-i)) { continue; } |
| 59 | + target.setCharAt(n-1-i, target.charAt(i)); |
| 60 | + } |
| 61 | + } |
| 62 | +} |
| 63 | +``` |
0 commit comments