+ 1
Rewrite the code using ternary operators
if(i%2==0) sum=sum-(int)k; else sum=sum+(int)k;
18 Réponses
+ 3
no all languages have ternary operator, and you don't provide the targeted one ^^
anyway, for languages that support it, ternary syntax commonly look like:
sum = i%2==0 ? sum-k : sum+k
for those wich doesn't support it, often you could inline if..else in the right hand side of an assignement (but syntax sligthly differ depending on language)
+ 2
you have a language for us?
sum - = int(k) if i%2==0 else sum+=int(k)
+ 2
value_if_true if condition else value_if_false
https://code.sololearn.com/clENZKjrst6t/?ref=app
+ 2
visph kotlin has none?
That's suprising!
thought it was Java under the hood. You found a reason for it?
+ 2
In java,
using ternary operator,
sum = i%2==0 ? sum-(int)k : sum+(int)k ;
+ 2
Jayakrishna🇮🇳 yes, that's what I was thinking, so I trust you easily ;)
just I'm not enough aware of Java (nor Kotlin) to answer without doubt (Kotlin wich I seen yesterday that ut doesn't have, surprising me and make me less sure that Javas has one)
+ 1
Frogged for what language is your example of inlined if..else?
+ 1
Java
+ 1
Neeta Maddheshiya I don't know if java has one or not: Kotlin doesn't have (I discovered that yesterday), and instead use:
sum = if (i%2==0) sum-k else sum+k
(assuming sum and k are of same type)
+ 1
Jayakrishna🇮🇳 I was not sure for Java, because I was thinking it has a ternary, but not Kotlin, so that make me doubt ^^
+ 1
visph Frogged
Java has it: https://www.baeldung.com/java-ternary-operator
Neeta Maddheshiya
See if you can do it by your own after reading about ternary on the site. If not, just ping me.
Happy coding!
+ 1
visph Java have ternary operator ?:
Am sure, it works..
I don't know about kotlin have it or not ..
0
Nor'wester 🌪️ 🇧🇩 are you sure?
because OP code seems not to be python ^^ (or invalid python ;P)
0
sorry for the typo corrected just after posting ;P