AcWing 1501. 回文数(Java)
原题链接
简单
作者:
码海泛舟
,
2020-07-18 09:59:17
,
所有人可见
,
阅读 606
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String A = sc.next();
int K = sc.nextInt();
ArrayList<Integer> num = new ArrayList<>();
for (int i = A.length() - 1; i >= 0; i--) {//低位在前,存储A
num.add(A.charAt(i) - '0');
}
int cnt = 0;//操作次数
if (!check(num)) {//如果num不是回文数
while (cnt < K) {
ArrayList<Integer> b = (ArrayList<Integer>) num.clone();
Collections.reverse(b);
num = add(num, b);
cnt++;
if (check(num)) break;
}
}
for (int i = num.size() - 1; i >= 0; i--) {
System.out.print(num.get(i));
}
System.out.println();
System.out.println(cnt);
}
private static ArrayList<Integer> add(ArrayList<Integer> num, ArrayList<Integer> b) {
ArrayList<Integer> c = new ArrayList<>();
int t = 0;
for (int i = 0; i < num.size() || i < b.size(); i++) {
if (i < num.size()) t += num.get(i);
if (i <b.size()) t += b.get(i);
c.add(t % 10);
t = t / 10;
}
if (t > 0) c.add(1);
return c;
}
private static boolean check(ArrayList<Integer> num) {
for (int i = 0, j = num.size() - 1; i < j; i++, j--) {
if (num.get(i) != num.get(j)) return false;
}
return true;
}
}