I have try to sum a number (29), by split it and sum the two numbers. But I have got some strange output. My code was:
When the input is 29 (n = 29)
fun addTwoDigits(n: Int): Int {
val n1 = n.toString()[0].toInt() // output: 50
val n2 = n.toString()[1].toInt() // output: 57
return n1+n2 // output: 107
}
Wy it is not getting the right numbers?
I sloved it by making
fun addTwoDigits(n: Int): Int {
val n1 = n.toString().substring(0,1).toInt() // output: 2
val n2 = n.toString().substring(1,2).toInt() // output: 9
return n1+n2 // output: 11
}
The n.toString().substring(1,2).toInt() gave me the right number. Please someone explain to me wy it is wrong?