+ 6
Help - Unexpected result
I have attached a small code showing my problem. Please help me to understand and resolve. https://code.sololearn.com/cFQ4UJHi37mW/?ref=app
12 Respuestas
+ 5
Yes. There would be a couple JVM bytecodes for Char to String plus a loop for String to Int (var sum=0;for (i in "$c"){sum*=10; sum+=i-'0'}) for the first versus three JVM bytecodes (Byte to Int twice Int+Int) for the second.
+ 4
Actually I don't know kotlin but I noticed that when you loop through the string and take one character, i is now type char and if you convert it to int it gonna give you asci of the char
So I did this
total += i.toString().toInt();
Am not sure it is the perfect answer but it did work
+ 4
Your i.toString().toInt() solution requires a lot more code to execute over the i-'0' one.
+ 3
This would also get 10. Char minus Char returns Int of difference. Int plus Char returns Char of sum.
for(i in num) {
total += i-'0'
}
+ 3
John Wells Thanks.
I have played with your suggestion and it works well, though will take me a bit longer to fully understand the concept.
+ 3
'1'-'0' = 49-48 = 1
'4'-'0' = 52-48 = 4
'5'-'0' = 53-48 = 5
+ 3
The Char class has this extended method defined.
operator fun Char.minus(other: Char): Int =
this.toInt()-other.toInt()
+ 3
John Wells Thanks again.
I understood that part, but I am getting my head around some of the advantages this approach provides, IE: cryptology, passwords, etc.
I think I am going to have some fun learning all this. 😁👍
+ 2
John Wells Thanks for showing me the extended method, it helps explain the background reasoning
+ 2
John Wells hence it would be slower?