美团测试开发岗编程题第二题

/*
通过率:73%
输出给定日期的2天后的日期
输入:
2018-05-01
输出:
2018-05-03
输入:
2018-05-30
输出:
2018-06-01
输入:
2018-05-32
输出:
error
*/

#include <iostream>
using namespace std;
//#include<stdio.h>
#include<string.h>

//判断闰年
int isLeapYear(int year) {
    //闰年:4年一润,百年不润,400年又润
    if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) {
        return 1;  //闰年
    }
    return 0;  //不是闰年
}

bool isValid(int year, int month, int day) {
    //月份数组,先假定不是闰年
    int daysOfMonth[] = { 31,28,31,30,31,30,31,31,30,31,30,31 };
    //判断闰年
    if (isLeapYear(year)) {
        daysOfMonth[1] = 29;  //将2月修改为29天
    }
    //判断是否合法日期
    if (year < 0 || month < 1 || month > 12 || day < 1 || day > daysOfMonth[month - 1]) {
        return false;
    }
    else {
        return true;
    }
}

//计算
void getNextDay(int year, int month, int day, int* nextYear, int* nextMonth, int* nextDay) {
    //月份数组,先假定不是闰年
    int daysOfMonth[] = { 31,28,31,30,31,30,31,31,30,31,30,31 };
    //判断闰年
    if (isLeapYear(year)) {
        daysOfMonth[1] = 29;  //将2月修改为29天
    }
    //判断是否为当月最后一天
    if (day == daysOfMonth[month - 1] || day == daysOfMonth[month - 1] - 1) {  //是最后一天或者倒数第2天
        //是否是最后一个月
        if (month == 12) {
            //下一年
            *nextYear = year + 1;
            *nextMonth = 1;
            if (day == daysOfMonth[month - 1]) {  //单月最后一天
                *nextDay = 2;
            }
            else {
                *nextDay = 1;  //否则是当月倒数第二天
            }
        }
        else  {
            //下个月
            *nextYear = year;
            *nextMonth = month + 1;
            if (day == daysOfMonth[month - 1]) {
                *nextDay = 2;
            }
            else {
                *nextDay = 1;
            }
        }
    }
    else {  //不是最后一天
        *nextYear = year;
        *nextMonth = month;
        *nextDay = day + 2;
    }
}

int main() {
    int year, month, day;
    int nextYear, nextMonth, nextDay;

    //输入日期
    char input[11];
    scanf("%s", input);

    //判断输入日期的格式
    char delimiter;
    if (strstr(input, "-") != NULL) {
        delimiter = '-';
    }
    else if (strstr(input, "/") != NULL) {
        delimiter = '/';
    }
    else
    {
        printf("error\n");
        return 0;
    }
    sscanf(input, "%d%c%d%c%d", &year, &delimiter, &month, &delimiter, &day);
    //scanf_s("%d-%d-%d", &year, &month, &day);

    //判断输入日期是否合法,否则会导致数组越界,结合年份月份天数
    //如:2018-05-32
    if (!isValid(year, month, day)) {
        printf("error\n");
        return 0;
    }
    //计算日期
    getNextDay(year, month, day, &nextYear, &nextMonth, &nextDay);
    //输出
    printf("%d-%02d-%02d\n", nextYear, nextMonth, nextDay);
    //结束
    return 0;
}
// 64 位输出请用 printf("%lld")

全部评论
我94 不知道少了哪个case😂
点赞 回复 分享
发布于 2023-09-09 13:42 北京

相关推荐

不愿透露姓名的神秘牛友
03-20 12:46
瘦嘟嘟右卫门:百度文库网盘的暑期也没约面吗
点赞 评论 收藏
分享
评论
点赞
1
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务