Java实现 蓝桥杯VIP 算法训练 回文数

在这里插入图片描述

import java.util.Scanner;


public class 回文数 {
	  static int time = 0;

	    public static int change(String str) {//十六进制转换为十进制
	        return Integer.valueOf(str,16);
	    }

	    public static String changeTo(int a) {//十进制转换为十六进制
	        return Integer.toHexString(a);
	    }


	    public static String reverse(String str) {
	        char[] arr = str.toCharArray();
	        for(int i = 0;i < arr.length / 2;i ++) {
	            char temp = arr[i];
	            arr[i] = arr[arr.length - 1 - i];
	            arr[arr.length - 1 - i] = temp;
	        }
	        String strReverse = "";
	        for(int i = 0;i < arr.length;i++) {
	            strReverse += arr[i];
	        }
	        return strReverse;
	    }

	    public static boolean jiance(String str) {
	        char[] arr = str.toCharArray();
	        for(int i = 0;i < arr.length / 2; i++) {
	            if(arr[i] != arr[arr.length - 1 - i]) {
	                return false;
	            }
	        }
	        return true;
	    }

	    public static String Jia(String a,String b,int jinzhi) {
	        char[] arr = a.toCharArray();
	        char[] brr = b.toCharArray();
	        String str = "";
	        int jinwei = 0;
	        for(int i = arr.length - 1;i >= 0;i --) {
	            int result = arr[i] + brr[i] + jinwei - 48 * 2;
	            jinwei = result / jinzhi;
	            str += String.valueOf(result % jinzhi);
	            if(i == 0 && jinwei != 0) {
	                str += String.valueOf(jinwei);
	            }
	        }
//	      System.out.println(reverse(str));
	        return reverse(str);
	    }

	    public static void huiwen(int jinzhi,String str) {
	        time ++;
	        char[] arr = str.toCharArray();
	        String strReverse = reverse(str);
	        String result;
	        if(jinzhi == 16) {
	            int flag = change(str) + change(strReverse);
	            result = changeTo(flag);
	        }else {
	            result = Jia(str,strReverse,jinzhi);
	        }
	        if(jiance(result) == false){
	            if(time >= 30) {
	                System.out.println("Impossible!");
	                return;
	            }
	            huiwen(jinzhi,result);

	        }else {
	            System.out.println("STEP=" + time);
	        }
	    }

	    public static void main(String[] args) {
	        Scanner sc = new Scanner(System.in);
	        int jinzhi = sc.nextInt();
	        String str = sc.next();
	        huiwen(jinzhi,str);
	    }

}

posted @ 2019-06-18 22:28  南墙1  阅读(28)  评论(0编辑  收藏  举报