Last active
December 20, 2019 02:03
-
-
Save sehajyang/1d995a09d773c28a0d8f99e94e7847b5 to your computer and use it in GitHub Desktop.
codility binary gap solution by scala
This file contains 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 solve(n: Int): Int = { | |
val input_seq = | |
Integer.toBinaryString(n).zipWithIndex.filter(_._1 == '1').map(_._2) | |
getGep(input_seq, input_seq.size - 1, 0) | |
} | |
@tailrec | |
def getGep(input_seq: IndexedSeq[Int], idx: Int, gap: Int): Int = { | |
if (idx == 0) { | |
if (gap == 0) 0 else gap - 1 | |
} else { | |
val now_gap = input_seq(idx) - input_seq(idx - 1) | |
if (now_gap > gap) getGep(input_seq, idx - 1, now_gap) | |
else getGep(input_seq, idx - 1, gap) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment