JAVA Blue Bridge Cup training algorithm palindrome

JAVA Blue Bridge Cup training algorithm palindrome

Resource constraints
Time limit: 1.0s Memory Limit: 256.0MB

Problem Description
  If a number (without the first zero) read from left to right and right to left reading all the same, we will call it palindrome.
  For example: Given a decimal number 56, 56 plus 65 (i.e., the 56 read from right to left), to give 121 is a palindrome.

Another example: for decimal 87:
  STEP1: 87 + 78 = 165 STEP2: 165 + 561 = 726
  STEP3: STEP4 726 + 627 = 1353: 1353 + 3531 = 4884

Here refers to a step in the N-ary addition, the steps in Example 4 to give a minimum palindrome 4884.

To write a program, a given N (2 <= N <= 10 or N = 16) hexadecimal number M (where hexadecimal digits 0-9 and the AF), at least after a short seek palindrome can be obtained.
  If (step 30 comprising a) can not be obtained within a palindrome in step 30, the output "Impossible!"

Input format
  two lines, N and M

Output format
  if step 30 can be obtained within a palindrome, the output "STEP = xx" (without the quotes), where xx is a number of steps; otherwise the output line (without the quotes) "Impossible!"

Sample input
. 9
87

Sample output
STEP = 6

import java.util.Scanner;

public class Main {
	public static void main(String[] args) {
		Scanner sca=new Scanner(System.in);
		int n=sca.nextInt();
		String m=sca.next();
		int index=0;
		while(!huiwen(m)) {
			index++;
			if(index>30) {
				break;
			}
			long tempa=Long.parseLong(m, n);
			String tt="";
			for(int i=m.length()-1;i>=0;i--) {
				String c=String.valueOf(m.charAt(i));
				tt+=c;
			}
			long tempb=Long.parseLong(tt, n);
			long sum=tempa+tempb;
			m=Long.toString(sum, n);
			
		}
		if(index>30) {
			System.out.println("Impossible!");
		}else {
			System.out.println("STEP="+index);
		}
	}
	public static boolean huiwen(String s) {
		boolean bo=true;
		for(int i=0;i<s.length()/2;i++) {
			if(s.charAt(i)!=s.charAt(s.length()-1-i)) {
				bo=false;
				break;
			}
		}
		return bo;
	}

}

Published 17 original articles · won praise 0 · Views 365

Guess you like

Origin blog.csdn.net/qq_36551453/article/details/104508834