{"id":252,"date":"2020-02-15T14:58:26","date_gmt":"2020-02-15T14:58:26","guid":{"rendered":"https:\/\/danwritescode.com\/?p=252"},"modified":"2020-06-22T13:13:34","modified_gmt":"2020-06-22T13:13:34","slug":"codility-lesson-1-javascript-solution-binary-gaps","status":"publish","type":"post","link":"https:\/\/danwritescode.com\/codility-lesson-1-javascript-solution-binary-gaps\/","title":{"rendered":"Codility Binary Gaps"},"content":{"rendered":"\n
This is a javascript implementation that renders a 100% correct solution of the Codility Lesson 1 challenge – Binary Gaps.<\/p>\n\n\n\n
I chose a recursive approach to this, and quite a simple solution. The performance is on point however.
We transform the integer into a string representation in binary of that integer.<\/p>\n\n\n\n
Then, we check for the first occurance of a 1, measure the gap to the next 1 and so on. There are tests to see if we reached the end, or if there’s only one “1” in the representation. And that’s all, folks.<\/p>\n\n\n\n
let gap;\nfunction solution(N) {\n \/\/ write your code in JavaScript (Node.js 8.9.4)\n if (N === parseInt(N, 10) && N>=1 && N<=2147483647){\n gap = 0;\n\n \/\/turn it to binary\n const binary = N.toString(2)\n \/\/turn it into an array\n let NArray = binary.split('')\n findGap(NArray)\n }\n return gap;\n \n}\n\n\n\nfunction evalGap(distance){\n if (distance > gap){\n gap = distance;\n }\n}\n\nfunction findGap(binaryArray) {\n if (binaryArray.indexOf('1') == -1){\n return gap\n } \n else {\n index1 = binaryArray.indexOf('1');\n evalGap(index1)\n\n binaryArray = binaryArray.slice(index1+1);\n index2 = binaryArray.indexOf('1')\n\n if (index2 !== -1) {\n\n evalGap(index2)\n binaryArray = binaryArray.slice(index2+1);\n findGap(binaryArray)\n } else {\n if (gap === 0) {\n gap = 0\n }\n }\n }\n}<\/code><\/pre>\n\n\n\n