leetcode刷题-2409-统计共同度过的日子数

题目:

Alice 和 Bob 计划分别去罗马开会。

给你四个字符串 arriveAlice ,leaveAlice ,arriveBob 和 leaveBob 。Alice 会在日期 arriveAlice 到 leaveAlice 之间在城市里(日期为闭区间),而 Bob 在日期 arriveBob 到 leaveBob 之间在城市里(日期为闭区间)。每个字符串都包含 5 个字符,格式为 "MM-DD" ,对应着一个日期的月和日。请返回 Alice和 Bob 同时在罗马的天数。假设所有日期都在 同一个 自然年,而且 不是 闰年。每个月份的天数分别为:[31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] 。

static int min(int a, int b){
    return a < b ? a : b;
}

static int max(int a, int b){
    return a > b ? a : b;
}

static int calulateDayOfYear(const char *day, const int *prefiSum){  //day是一个返回字符型数据的指针 
    int month = (day[0] - '0') * 10 + day[1] - '0';
    int date = (day[3] - '0') * 10 + day[4] - '0';
    return prefiSum[month - 1] + date;
}

int countDaysTogether(char *arriveAlice, char *leaveAlice, char *arriveBob, char *leaveBob){
    int datesOfMonths[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
    int prefiSum[13];
    prefiSum[0] = 0;
    for(int i = 0; i < 12; i++){
        prefiSum[i + 1] = prefiSum[i] + datesOfMonths[i];
    }
    int arriveAliceDay = calulateDayOfYear(arriveAlice, prefiSum);
    int leaveAliceDay = calulateDayOfYear(leaveAlice, prefiSum);
    int arriveBobDay = calulateDayOfYear(arriveBob, prefiSum);
    int leaveBobDay = calulateDayOfYear(leaveBob, prefiSum);
    return max(0, min(leaveAliceDay, leaveBobDay) - max(arriveAliceDay, arriveBobDay) + 1);
}

补充:

1.用static修饰局部变量,其实就是改变了变量的存储类型,使其从栈区存储变为静态区,使静态的局部变量出了作用域也不被释放,生命周期也变的和全局变量一样,都是程序结束后才释放。

2.函数本身就具有外部链接属性,当使用static修饰时使其的外部链接属性变为内部链接属性,从而使函数只能在自己的源文件中使用,不能再工程的其他内部源文件使用。

3.const和指针的结合使用

常量指针:

int a = 100;
const int *p = &a;
或
int const *p = &a;
const修饰指针变量的类型,可直接修改变量值,不可修改指针指向的地址里的内容(编译报错),可以修改指针的指向

指针常量:

int a = 5;
int * const p = &a;

可以直接修改变量的值,可以修改指针指向地址的内容,但是不能修改指针的指向(编译报错)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值