Programming/Kotlin

[Kotlin] ์ž…๋ ฅ ๋ฐ›์€ ๋‚ ์งœ๋กœ ๊ฒฝ๊ณผ์ผ์ˆ˜ ๊ตฌํ•˜๋Š” ๋ฐฉ๋ฒ• (get the day of the year as an integer in Kotlin)

yuri lee 2023. 3. 2. 18:09
๋ฐ˜์‘ํ˜•

Intro

์•ˆ๋…•ํ•˜์„ธ์š”. ์ด๋ฒˆ ์‹œ๊ฐ„์—๋Š” ์ฝ”ํ‹€๋ฆฐ์—์„œ ์ž…๋ ฅ ๋ฐ›์€ ๋‚ ์งœ๋กœ ๊ฒฝ๊ณผ์ผ์ˆ˜๋ฅผ ๊ตฌํ•˜๋Š” ๋ฐฉ๋ฒ•์— ๋Œ€ํ•ด ์•Œ์•„๋ณด๊ฒ ์Šต๋‹ˆ๋‹ค. 

 

How to solve the problem

์•„๋ž˜ ์ฝ”๋“œ๋ฅผ ํ™œ์šฉํ•˜๋ฉด ์ž…๋ ฅ ๋ฐ›์€ ๋‚ ์งœ๋กœ ํ•ด๋‹น ๊ฒฝ๊ณผ ์ผ์ˆ˜๋ฅผ ๊ตฌํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. 

/**
 * You can edit, run, and share this code.
 * play.kotlinlang.org
 */
fun main() {
    // ์œค๋…„ ํŒ๋ณ„ ๋ฉ”์†Œ๋“œ (1 ์œค๋…„, 0 ํ‰๋…„)
    fun isLeap(year: Int): Int {
        return if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) 1 else 0
    }
     
    fun dayOfYear(year: Int, month: Int, day: Int): Int {
    	val days = arrayOf(intArrayOf(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31), intArrayOf(31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31))
    	var day = day
    	for (i in 0 until month - 1) {
        	day += days.get(isLeap(year)).get(i)
    	}
    	return day
	}
	println((dayOfYear(2023, 3, 2)))
}

 

2023๋…„ 3์›” 2์ผ ๋‚ ์งœ๊ธฐ์ค€์œผ๋กœ 61์ผ์ด ๋‚˜์˜ต๋‹ˆ๋‹ค. 

61

 

์‹ค์ œ ๊ฒฐ๊ณผ๊ฐ€ ๊ถ๊ธˆํ•˜์‹  ๋ถ„๋“ค์€ ์•„๋ž˜ kotlin playground์—์„œ ์‹คํ–‰์‹œ์ผœ๋ณด์‹œ๊ธธ ๋ฐ”๋ž๋‹ˆ๋‹ค.

https://play.kotlinlang.org/

๋ฐ˜์‘ํ˜•