+ 1
Parking Fee Question in Kotlin course
Okay, so as per the question, i have set the code and there are 6 test cases. 3 are passing while other 3 are failing 😂. Please someone help me and tell me what is the problem in my code ? fun main(args: Array<String>) { var hours = readLine()!!.toInt() var total: Double = 0.0 for(i in 1..hours){ if(i<=5){ total += 1.0 }else if(i>5 && i<24){ total += 0.5 }else{ total = 15.0 + (0.5*(hours-24)) break } } println(total) } Thanks for help.
11 Respuestas
+ 4
Parking Fee question answer is 👇
fun main(args: Array<String>) {
var hours = readLine()!!.toInt()
var total: Double = 0.0
if (hours>=24) {
var days: Int = 0
days = hours/24
total = days*15+(hours-days*24)*0.5
}
else if (hours>5) {
total = 5+(hours-5)*0.5
}
else {
total = hours*1.0
}
println(total)
}
+ 3
Manmeet
There maybe more than 48 hours so else condition will be like this:
total = 15 * (hours / 24) + 0.5 * (hours % 24)
+ 3
Manmeet
There maybe more than 48 hours so we have to divide with 24 to get exact days and we have to use Modulus Operator (%) to get remaining hours.
So if there is 49 hours then 49 / 24 will give 2 days and for remaining 1 hour we have to use modulus operator.
So (49 / 24) = 2 days
and (49 % 24) = 1 hours
So according to 15$ / days = 2 * 15
According to 0.5$ /hours = 0.5 * 1
+ 3
fun main(args: Array<String>) {
var hours = readLine()!!.toInt()
var total: Double = 0.0
when{
hours in 1..5 -> total = hours.toDouble()
hours in 6 until 24 -> total = (hours - 5)*0.5 + 5
hours >= 24 -> total = (hours/24).toDouble() *15 + (hours%24)*0.5
}
println(total)
}
Более изящно, без циклов и лишних переменных)
+ 1
Bot isn't break statement breaking the loop on first iteration ?
+ 1
Simba Thanks bro, I had searched for this answer but didnt get why they were dividing hours by 24. Thanks a lot again.
+ 1
🅰🅹 🅐🅝🅐🅝🅣 Thanks bro
0
you are adding 15 plus additional charges of 0.5*(hours-24) on every iteration when the additional charge should be added only once
0
ah yes sorry didn't notice that, but then you didnt have $15 for every 24 hours, you only have $15 for first 24 hours
- 1
fun main(args: Array<String>) {
var hours = readLine()!!.toInt()
var total: Double = 0.0
var prifix = when {
hours in 6..23 -> 5
hours >= 24 -> 15
else -> 0
}
val price: Double = when {
hours in 1..5 -> 1.0
hours in 6..23 -> 0.5
hours >= 24 -> 0.5
else -> 0.0
}
if (hours >= 24) {
prifix *= hours / 24
hours %= 24
total = prifix + (hours * price)
}
else if (hours in 6..23) {
hours -= 5
total = prifix + (hours * price)
}
else{
total = hours * price
}
println(total)
}