Last active
March 7, 2021 08:15
-
-
Save michalbcz/b47f9c8d74b92eb089eff98c8645db5b to your computer and use it in GitHub Desktop.
DEC to HEX puzzler (see gist's revision for problem and diff to this solution)
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
/* THIS PUZZLER IS SOVLED, SEE REVISION OF THIS GIST TO SEE ORIGINAL PROBLEM */ | |
decimalValue = 9989 | |
hexValue = toHex(code) | |
assert hexValue == '2705' | |
// safe net | |
expectedValue = Integer.toHexString(decimalValue) | |
assert hexValue == expectedValue : "Your impl should work as expected. Result should be: ${expectedValue}" | |
println "DECIMAL VALUE: ${decimalValue} CONVERTED TO HEX VALUE: ${hexValue}" | |
/* ------------------------ METHODS -------------------------- */ | |
/* | |
note you can use Java's Integer#toHexString() | |
this is just for practicing purposes | |
*/ | |
def toHex(number) { | |
next = Double.valueOf(Math.floor(number / 16)).toLong() | |
def remainder = number % 16 | |
// debug print to see what happens inside of this method | |
// println next + ", " + remainder | |
// translate 10 -> A, 11->B .... 15->F | |
if (remainder > 9) { | |
remainder = (((int)'A') + (remainder - 10)) as char | |
} | |
// end recursion | |
if (next == 0) { | |
return remainder | |
} | |
return toHex(next) + remainder.toString() | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment