Created
March 12, 2019 00:04
-
-
Save jonpemby/851eaeaeddd587b52019805993dba3c2 to your computer and use it in GitHub Desktop.
Kotlin parseInt
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
fun parseInt(s: String): Int { | |
var num = 0 | |
var j = 1 | |
var i = s.length - 1 | |
while (i >= 0) { | |
val c = s[i].toInt() | |
if (c < 48 || c > 58) { | |
i -= 1 | |
continue | |
} | |
num += powBase10(j - 1) * (c - 48) | |
i -= 1 | |
j += 1 | |
} | |
return num | |
} | |
fun powBase10(a: Int): Int { | |
if (a < 0) { | |
return 10 | |
} | |
if (a == 0) { | |
return 1 | |
} | |
return 10 * powBase10(a - 1) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Didn't code negative powers of 10 but it works for positive powers of 10 😄