Created
October 16, 2018 17:13
-
-
Save DVegasa/0cc081b97764faa3625c0601d10e5f3d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package io.github.dvegasa; | |
import org.junit.platform.commons.annotation.Testable; | |
import java.math.BigInteger; | |
import java.util.Scanner; | |
public class Main { | |
public static void main(String[] args) { | |
Scanner sc = new Scanner(System.in); | |
System.out.println(nextPalindrom(sc.nextLine())); | |
} | |
public static String nextPalindrom(String number) { | |
BigInteger num = new BigInteger(number); | |
if (isPalindrom(num.toString())) { | |
num = num.add(BigInteger.ONE); | |
if (isPalindrom(num.toString())) { | |
return num.toString(); | |
} | |
} | |
// v v | |
int iM = num.toString().length() / 2; // середина числа 12345 1234 | |
int iPosR = num.toString().length() - 1; | |
for (; iPosR >= iM; iPosR--) { | |
int iPosL = num.toString().length() - 1 - iPosR; | |
char l = num.toString().charAt(iPosL); | |
char r = num.toString().charAt(iPosR); | |
if (l != r) { | |
if (r > l) { | |
// Повышаем разряд числа | |
int zeros = num.toString().length() - iPosR; | |
StringBuilder toAdd = new StringBuilder("1"); | |
for (int i = 0; i < zeros; i++) { | |
toAdd.append("0"); | |
} | |
num = num.add(new BigInteger(toAdd.toString())); | |
} | |
// Заменяем цифры с правого конца на цифры [iPosL] с левого, чтобы совпадали | |
char[] newString = num.toString().toCharArray(); | |
newString[iPosR] = num.toString().charAt(iPosL); | |
num = new BigInteger(new String(newString)); | |
} | |
} | |
return num.toString(); | |
} | |
@Testable | |
public static boolean isPalindrom(String num) { | |
for (int i = 0; i < num.length() / 2; i++) { | |
if (!(num.charAt(i) == num.charAt(num.length() - 1 - i))) { | |
return false; | |
} | |
} | |
return true; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
// All tests passed