Skip to content

Instantly share code, notes, and snippets.

@jonpemby
Created March 12, 2019 00:04
Show Gist options
  • Save jonpemby/851eaeaeddd587b52019805993dba3c2 to your computer and use it in GitHub Desktop.
Save jonpemby/851eaeaeddd587b52019805993dba3c2 to your computer and use it in GitHub Desktop.
Kotlin parseInt
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)
}
@jonpemby
Copy link
Author

Didn't code negative powers of 10 but it works for positive powers of 10 😄

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment