每日算法7:日期的二进制转换

【问题】

求日期1964年10月10日到2020年7月24日之间,日期做以下处理,还得到最初日期一致?

①日期转化为yyyyMMdd格式字符串

②转化为二进制数

③逆序排列

④二进制转十进制

【算法】

public static void main(String[] args) {

      System.out.println("日期:" + DateUtil.GetDate(new Date(1964-1900, 10-1, 10),new Date(2020-1900, 7-1, 24)));

  }

  /**

  * 日期

  */

  public class DateUtil {

    public static int GetDate(Date start, Date end){

        int count = 0;

        Date currentDate = start;

        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");

        while(currentDate.before(end)){

            //日期转格式字符串

            String dd = formatter.format(currentDate);

            if(GetDate2(dd)){

                System.out.print(dd+",");

                count++;

            }

            Calendar c = Calendar.getInstance();

            c.setTime(currentDate);

            c.add(Calendar.DAY_OF_MONTH, 1);// 今天+1天

            currentDate = c.getTime();

        }

        return count;

    }

    public static boolean GetDate2(String date){

        //转化为二进制

        BigInteger bi = new BigInteger(date); //转换成BigInteger类型

        String d2 = bi.toString(2); //参数2指定的是转化成X进制,默认10进制

        //反转

        String d3 = new StringBuffer(d2).reverse().toString();

        //转化为10进制

        BigInteger d5 = new BigInteger(d3, 2); //转换为BigInteger类型

        if(bi.equals(d5)){

            return true;

        }else{

            return false;

        }

    }

}

【答案】19660713,19660905,19770217,19950617,20020505,20130201,日期:6

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容