+ 1
Can anyone help me refactor this code?
This code passed the test cases but I think the control flow can be refactored. Any idea? fun main(args: Array<String>) { var hours = readLine()!!.toInt() var total: Double = 0.0 if(hours < 24){ if(hours <= 5){ //first 5 hours is $1/hour total += (hours * 1) } else { total += 5 //remaining hours is $0.5/hour var rhours = hours - 5 total += (rhours * 0.5) } } else { var day: Int = (hours/24).round() var rhours: Int = hours%24 //flat rate $15/day total += (day *15) total += (rhours*0.5) } println(total) } P/S This is a code snippet from Kotlin's project.
1 Réponse
0
You can do something like :
fun main(args: Array<String>) {
var hours = readLine()!!.toInt()
when (hours) {
in 0..5 -> print(hours);
in 6..23 -> print(5+(hours-5)*0.5);
else -> print((hours/24).round()*15 + hours%24*0.5)
}
}