'Solo Learn practice how to calculate parking fee based on some conditions in Kotlin
You are making a car parking software that needs to calculate and output the amount due based on the number of hours the car was parked. The fee is calculated based on the following price structure:
- the first 5 hours are billed at $1 per hour.
- after that, each hour is billed at $0.5 per hour.
- for each 24 hours, there is a flat fee of $15.
This means, that, for example, if a car parked for 26 hours, the bill should be 15+(2*0.5) = 16.0, because it was parked for 24 hours plus 2 additional hours.
Sample Input: 8
Sample Output: 6.5
Explanation: The first 5 hours are billed at $1/hour, which results in $5. After that, the next 3 hours are billed at $0.5/hour = $1.5. So, the total would be $5+$1.5 = $6.5
Below code works fine however it doesn't satisfy all conditions which are hidden
fun main(args: Array<String>) {
var hours = readLine()!!.toInt()
var total: Double = 0.0
total = when{
hours <= 5 -> {
val cost = hours *1.toDouble()
cost
}
hours in 6..23 -> {
val cost = 5 + (hours - 5) * 0.5
cost
}
hours == 24 -> {
val cost = 15.toDouble ()
cost
}
else -> {
val cost = 15 + (hours -24) * 0.5
cost
}
}
println(total )
}
Solution 1:[1]
One case that I think you missed is that, for hours > 24
you always use $15, while as per the question it is $15 per day, so you need to multiply it by the number of days.
Try this code:
fun main(args: Array<String>) {
val hours = readLine()!!.toInt()
val total = when {
hours >= 24 -> 15 * (hours / 24) + 0.5 * (hours % 24)
hours > 5 -> 5 + (hours - 5) * 0.5
else -> hours.toDouble()
}
println(total)
}
Solution 2:[2]
Try this code:
fun main (args : Array<String>) {
var hour = readLine()!!.toInt()
var total = when {
hour >= 24 -> (15 * (hour/24)) + (0.5 * (hour%24))
hour > 5 && hour <24 -> 5 + ((hour-5)*0.5)
else -> hour.toDouble()
}
println(total)
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Arpit Shukla |
Solution 2 | Mihir Kumar Singh |