Created
April 26, 2015 15:33
-
-
Save AhmedSoliman/44fcfd8b4b81a8140487 to your computer and use it in GitHub Desktop.
A sample quiz answer on how to create toString without relying on primitive toString method for integers
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
def customToString(x: Int): String = { | |
val digits: Array[Char] = Array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9') | |
def recur(base: Int, digit: Int, accu: List[Char]): List[Char] = { | |
val newAcc = digits(digit) :: accu | |
if (base == 0) newAcc | |
else recur(base / 10, base % 10, newAcc) | |
} | |
val absX = math.abs(x) | |
val toCharList = recur(absX / 10, absX % 10, List.empty) | |
if (x < 0) ('-' :: toCharList).mkString | |
else toCharList.mkString | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
here's my solution in Haskell