闰年判断

一年中的第几天-闰年判断

class Solution {
public:
  int dayOfYear(string date) {
    int ans = 0;
    bool isRun;
    int year = (date[0] - '0') * 1000 + (date[1] - '0') * 100 +
               (date[2] - '0') * 10 + (date[3] - '0') * 1;
    int month = (date[5] - '0') * 10 + (date[6] - '0') * 1;
    int day = (date[8] - '0') * 10 + (date[9] - '0') * 1;

    if (year % 4 == 0) {
      if (year % 100 == 0) {
        // // 这里如果被 400 整除是闰年
        if (year % 400 == 0)
          isRun = 1;
        else
          isRun = 0;
      } else
        isRun = 1;
    } else
      isRun = 0;
    int lastday;
    for (int i = 1; i <= month; i++) {
      if (i == 1 || i == 3 || i == 5 || i == 7 || i == 8 || i == 10 ||
          i == 12) {
        ans += 31;
        lastday = 31;
      } else if (i == 2) {
        if (isRun) {
          ans += 29;
          lastday = 29;
        } else {
          ans += 28;
          lastday = 28;
        }
      } else {
        ans += 30;
        lastday = 30;
      }
    }
    ans -= (lastday - day);
    return ans;
  }
};

 

上一篇:laravel MySQL union all 查询分页


下一篇:Python format() 强化