Last active
June 29, 2020 00:39
-
-
Save dayanruben/178672edba4d8648a13ca3ac60a6a386 to your computer and use it in GitHub Desktop.
Base62 encoding/decoding
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
| class Base62 { | |
| val order = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" | |
| val base = order.length | |
| fun encode(number: Int): String { | |
| var num = number | |
| var res = "" | |
| while (num > 0) { | |
| res = "${order[num % base]}$res" | |
| num /= base | |
| } | |
| return res | |
| } | |
| fun decode(code: String): Int { | |
| val reversedCode = code.reversed() | |
| return code.indices.sumBy { i -> Math.pow(base.toDouble(), i.toDouble()).toInt() * order.indexOf(reversedCode[i])} | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment