Java实现 洛谷 P1015 回文数(N进制回文数)-LMLPHP

输入输出样例

输入样例#1:

10

87

输出样例#1:

STEP=4

import java.util.Scanner;

public class 回文数2 {
public static void main(String[] args) {
Scanner sc =new Scanner(System.in);
int n = sc.nextInt();
String m = sc.next();
int [] num = new int [51];
int [] num1 = new int [51];
int count=0; for (int i = 1; i < m.length()+1; i++) {
if (m.substring(i-1, i).equals("A")) {
num[i]=10;
}
else if(m.substring(i-1, i).equals("B")){
num[i]=11;
}
else if(m.substring(i-1, i).equals("C")){
num[i]=12;
}
else if(m.substring(i-1, i).equals("D")){
num[i]=13;
}
else if(m.substring(i-1, i).equals("E")){
num[i]=14;
}
else if(m.substring(i-1, i).equals("F")){
num[i]=15;
}
else {
num[i]=Integer.valueOf(m.substring(i-1,i));
} }
// for (int i = 1; i < num.length; i++) {
//
// num[i]=m%n;
// m/=n;
// }
int a=0;//首位数字
int i=0;
for ( i = 1; i <=30; i++) {
for (int j = num.length-1; j >0; j--) {
if(num[j]!=0){
a=j;
break;
}
}
for (int j = a; j >0; j--) {
num1[a-j+1]= num[j];
}
boolean bool = true;
for (int j = 0; j < num1.length; j++) {
if(num[j]!=num1[j]){
bool=false;
}
}
if (bool) {
System.out.println("STEP="+count);
break;
}
int b =0;
for (int j = 1; j < num1.length; j++) {
num[j]=num[j]+num1[j]+b;
b=num[j]/n;
num[j]%=n;
}
count++;
}
if(i==31){
System.out.println("Impossible!");
}
} }
05-20 12:41