Blue Bridge Cup ADV-389 palindrome date java

Problem Description

Sample input

20200202

Data

Sample output

20211202
21211212

Data

Evaluation use case scale and conventions

For all evaluation cases, 10000101≤N≤89991231, to ensure that N is an 8-digit representation of a legal date.

Problem-solving ideas

1. The date required by the title is the number of palindromes, so we only need the first four violent and the last four palindromes to make up

		for (int i = n + 1; i < 9999; i++) 
			//将字符串后4位翻转
			StringBuilder sb = new StringBuilder(i + "");
			sb.reverse();
			//拼接字符串形成回文数
			String date = i + "" + sb;

2. The number of violent palindromes must be judged by the legal date

	private static boolean isDate(String date) {//验证日期合法性
		boolean result = true;
		// SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
		SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
		try {
			//要将setLenient设为false
			//否则SimpleDateFormat会比较宽松地验证日期,比如2007/02/29会被接受,并转换成2007/03/01
			format.setLenient(false);
			format.parse(date);
		} catch (ParseException e) {
			// 如果throw java.text.ParseException或者NullPointerException,就说明格式不对
			result = false;
		}
		return result;
	}

3. Independent method to judge and verify the ABAB type date. Now that it is a palindrome, there is no need to judge the last four digits

return (str[0] != str[1] && str[0] == str[2] && str[1] == str[3]);

Reference Code

package 回文日期;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Scanner;

public class Main {
	public static void main(String[] args) {
		Scanner sr = new Scanner(System.in);
		//初始我们将第一个出现的回文数,abab型的回文数都设为空.也是结束程序的条件
		String frist = null;
		String abab = null;
		int n = sr.nextInt() / 10000;//我们只取到前四位就可以了
		for (int i = n + 1; i < 9999; i++) {
			//将字符串后4位翻转
			StringBuilder sb = new StringBuilder(i + "");
			sb.reverse();
			//拼接字符串形成回文数
			String date = i + "" + sb;
			//两个日期都获得值了,结束循环
			if(abab != null && frist != null)break;
			//计算日期合法性,ABAB性
			if (isDate(date)) {// 验证合法日期
				if (frist == null)//第一个出现的回文日期
					frist = date;
				if (abab == null && isABAB(date))//第一个出现的回文ABAB日期
					abab = date;
			}
		}
		//结果输出
		System.out.println(frist);
		System.out.println(abab);
	}

	private static boolean isABAB(String date) {//验证ABAB型日期
		char[] str = date.toCharArray();
		//即然是回文数,就不用判断后四位了
		return (str[0] != str[1] && str[0] == str[2] && str[1] == str[3]);
	}

	private static boolean isDate(String date) {//验证日期合法性
		boolean result = true;
		// SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
		SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
		try {
			//要将setLenient设为false
			//否则SimpleDateFormat会比较宽松地验证日期,比如2007/02/29会被接受,并转换成2007/03/01
			format.setLenient(false);
			format.parse(date);
		} catch (ParseException e) {
			// 如果throw java.text.ParseException或者NullPointerException,就说明格式不对
			result = false;
		}
		return result;
	}
}

 

Guess you like

Origin blog.csdn.net/qq_40185047/article/details/114987196