LeetCode1154 一年中的第几天

LeetCode 1154

注意点:

  1. 闰年是 能被4整除 且 不能被100 整除, 或者可以被 400 整除
  2. 对于 C/C++ stdlib 中的 atoi函数, int atoi(const char *str);
    该函数将字符串转换为int型整数,返回转换后的长整数,如果没有执行有效的转换,则返回零。
  3. C++中的string类型, 需要通过 date.c_str() 为 char* 类型。

Java学习

1. String 中的substring方法:
// str.substring(int n); // 从n开始到末尾
// str.substring(int n, int m); // 从n开始到m , 长度为 m - n

2. string 和 int 格式的互换
// Integer.parseInt( s );
*3. Java数组 **
// int[] arr = {};
// int[] arr; arr = new int[n];
4. Java 输入
/
Scanner sc = new Scanner(System.in);
String name = sc.nextLine();
*/

题目:Given a string date representing a Gregorian calendar date formatted as YYYY-MM-DD, return the day number of the year.

Example 1:

Input: date = “2019-01-09”
Output: 9
Explanation: Given date is the 9th day of the year in 2019.
Example 2:

Input: date = “2019-02-10”
Output: 41
Example 3:

Input: date = “2003-03-01”
Output: 60
Example 4:

Input: date = “2004-03-01”
Output: 61

Constraints:

date.length == 10
date[4] == date[7] == ‘-’, and all other date[i]'s are digits
date represents a calendar date between Jan 1st, 1900 and Dec 31, 2019.

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/ordinal-number-of-date
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

// C语言
int dayOfYear(char* date)
    {
    int days[]={31,28,31,30,31,30,31,31,30,31,30,31};
    int i;
    int year = atoi(date);		// atoi 中参数为const char * 类型
    int month = atoi(date+5);
    int day = atoi(date+8);
    //cout << year <<" "<
// C++代码
class Solution {
public:
    int dayOfYear(string date)
    {
    int days[]={31,28,31,30,31,30,31,31,30,31,30,31};
    int i;
    const char* s;
    s = date.c_str();		// 可以将string 类型转为 char *类型
    int year = atoi(s);
    int month = atoi(s+5);
    int day = atoi(s+8);
    //cout << year <<" "<

Java代码

package DayOfTheYear1154;

class Solution {
	public int dayOfYear(String date) {
			int[] table = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
			String year = date.substring(0, 4);
			String month = date.substring(5, 7);
			String day = date.substring(8, 10);
			int y = Integer.parseInt(year);
			int m = Integer.parseInt(month);
			int d = Integer.parseInt(day);
			if((y % 4==0&& y%100!=0) || (y%400==0))
					table[1] = 29;
			int ans = 0;
			for(int i=0;i

你可能感兴趣的:(Java,C++,LeetCode题目)