1 条题解

  • 0
    @ 2023-12-18 18:22:14

    大牛用的Java算法比我的时间少了一半,好厉害orz,说来惭愧,这种简单的模拟题写了一个半小时,菜还是得多练啊,注意int转float的时候把除数加上浮点数标识'f',不然会被自动识别成整型,被自动转换掉导致结果出错

    import java.util.Scanner;
    
    public class Main {
        public static void main(String[] args) {
            Scanner sc = new Scanner(System.in);
            System.out.println("Initial time  Final time  Passes");
            while (sc.hasNextInt())
            {
                //输入
                int hour1 = sc.nextInt();
                int minute1 = sc.nextInt();
                int hour2 = sc.nextInt();
                int minute2 = sc.nextInt();
    
                int encounterNum = Encounter(hour1,hour2,minute1,minute2);
    
                String time1 = StandardOutput(hour1,minute1);
                String time2 = StandardOutput(hour2,minute2);
    
                System.out.printf("%12s%12s%8d\n",time1,time2,encounterNum);//右对齐输出
    
            }
        }
        //此方法计算时针分针相交次数
        public static int Encounter(int hour1,int hour2,int minute1,int minute2){
            int count = 0;//计数器
            int hour = hour2 - hour1;//小时差
            int minute = minute2 - minute1;//分钟差
            //手动模拟减肥退位运算orz
            if(minute < 0) {
                minute += 60;
                hour--;
            }
            if(hour < 0){
                hour += 12;
            }
    
            //总分钟差
            minute += hour * 60;
    
            float initialHour = ((hour1 % 12f + minute1 / 60f) / 12f);//时针初始值,单位为圈(round),比如小时为3就是3/12=0.25圈
    
            float initialMinute = (minute1 / 60f);//分钟初始值,单位为圈
    
            float minuteDifference = (initialHour - initialMinute);//初始值差
            if(minuteDifference < 0){
                minuteDifference += 1f;
            }
    
            float round = minute / 60f * 11f / 12f;//追及问题,时针和分针的相对角速度为 11/12 round/h,则分钟化为小时后*11/12
            count += (int)round;//向下取余加到计数器
            //多余的小数如果大于初始值差则说明一开始不满第一圈的时候也会相遇一次
            if(round - count >= minuteDifference)
            {
                count++;
            }
    
            return count;
    
        }
        //标准化输出
        public static String StandardOutput(int hour,int minute){
            String time = ":";
            if(hour < 10){
                time = "0"+hour+time;
            }else {
                time = hour+time;
            }
            if(minute < 10)
            {
                time += "0"+minute;
            }else {
                time += minute;
            }
            return time;
        }
    }
    

    信息

    ID
    6
    时间
    1000ms
    内存
    32MiB
    难度
    9
    标签
    递交数
    15
    已通过
    3
    上传者