原题链接
自己最先的思路比较直接,是遍历每一个日期,然后判断这个日期是否是回文
调库的写法会超时,下面是不调库的写法。
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int begin=sc.nextInt(),end=sc.nextInt();
ff(begin,end);
}
public static int[] days= {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
static void ff(int begin,int end) {
int res=0,temp=0;
int a=begin/10000,b=((begin%10000)/100),c=(begin%100);
StringBuffer sb = new StringBuffer();
while(temp<=end) {
sb.setLength(0);
temp=a*10000+b*100+c;
sb.append(temp);
if(sb.toString().equals(sb.reverse().toString())) {res++;}
c++;
if(a%4==0&&a%100!=0||a%400==0)if(c==29)continue;
if(c>days[b]) {
c=1;b++;
if(b>12) {b=1;a++;}
}
}
System.out.println(res);
}
}
看别人题解的方法
import java.util.Scanner;
public class Main {
public static int[] days= {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
//StringBuffer begin=new StringBuffer(sc.next()),end=new StringBuffer(sc.next());
int begin=sc.nextInt(),end=sc.nextInt();
yxc(begin,end);
}
public static boolean check(int date)
{
int year = date / 10000;
int month = date % 10000 / 100;
int day = date % 100;
if (month==0 || month >=13 || day==0) return false;
if (month != 2 && day > days[month]) return false;
if (month == 2) {
boolean leap = (year % 4 == 0 )&&(year % 100!=0) ||(year % 400 == 0);
if(leap&&day>29)return false;
if(!leap&&day>28)return false;
}
return true;
}
public static void yxc(int begin,int end) {
int res = 0;
for (int i = 0; i < 10000; i ++ ){
int x = i, r = i;
for (int j = 0; j < 4; j ++ ) {r = r * 10 + x % 10;x /= 10;}
if (r >= begin && r <= end && check(r)) res ++ ;
}
System.out.println(res);
}
}