+ 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

8th Oct 2020, 10:14 PM
Rik Wittkopp
Rik Wittkopp - avatar
12 odpowiedzi
+ 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.
11th Oct 2020, 9:26 AM
John Wells
John Wells - avatar
+ 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
8th Oct 2020, 10:26 PM
Ruba Kh
Ruba Kh - avatar
+ 4
Your i.toString().toInt() solution requires a lot more code to execute over the i-'0' one.
11th Oct 2020, 9:10 AM
John Wells
John Wells - avatar
+ 3
Ruba Kh , Mirielle , Thanks
8th Oct 2020, 11:23 PM
Rik Wittkopp
Rik Wittkopp - avatar
+ 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' }
11th Oct 2020, 6:58 AM
John Wells
John Wells - avatar
+ 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.
11th Oct 2020, 8:30 AM
Rik Wittkopp
Rik Wittkopp - avatar
+ 3
'1'-'0' = 49-48 = 1 '4'-'0' = 52-48 = 4 '5'-'0' = 53-48 = 5
11th Oct 2020, 8:52 AM
John Wells
John Wells - avatar
+ 3
The Char class has this extended method defined. operator fun Char.minus(other: Char): Int = this.toInt()-other.toInt()
11th Oct 2020, 8:57 AM
John Wells
John Wells - avatar
+ 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. 😁👍
11th Oct 2020, 9:06 AM
Rik Wittkopp
Rik Wittkopp - avatar
+ 2
John Wells Thanks for showing me the extended method, it helps explain the background reasoning
11th Oct 2020, 9:10 AM
Rik Wittkopp
Rik Wittkopp - avatar
+ 2
John Wells hence it would be slower?
11th Oct 2020, 9:12 AM
Rik Wittkopp
Rik Wittkopp - avatar