Resolvi treinar um pouco de lógica de programação pelo Codility e, por isso, pretendo realizar uma série de postagens publicando minha resposta dos exercícios feitos. Não irei descrever o problema, portanto, caso queira acompanhar e entender o objetivo do código, peço que entre no site do Codility, faça seu cadastro e vá na seção Lessons. Utilizei o Visual Studio Code para escrever meu código e o NodeJs para rodá-lo dando o comando "node nome_do_arquivo.js".
Hoje resolvi o exercício BinaryGap usando Javascript. Veja o código a seguir:
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
console.log(solution(9)); | |
function solution(N) { | |
const range = [1, 2147483647]; | |
if(N >= range[0] && N <= range[1]) { | |
var binary = decimalToBinary(N); | |
return maxBinaryGap(binary); | |
} | |
return 0; | |
} | |
function isGapStart(firstChar, secondChar) { | |
return firstChar == '1' && secondChar == '0'; | |
} | |
function isGapEnd(firstChar, secondChar) { | |
return firstChar == '0' && secondChar == '1'; | |
} | |
function maxBinaryGap(binary) { | |
var endIndex = binary.length - 1; | |
var gapCounter = 0; | |
var mustCount = false; | |
var tempCounter = 0; | |
var firstChar = ''; | |
var secondChar = ''; | |
for(var i = 0; i < endIndex; i++) { | |
firstChar = binary.charAt(i); | |
secondChar = binary.charAt(i + 1); | |
if(isGapStart(firstChar, secondChar)) { | |
mustCount = true; | |
tempCounter = 0; | |
} | |
if(isGapEnd(firstChar, secondChar)) { | |
if(mustCount) { | |
mustCount = false; | |
if(tempCounter > gapCounter) { | |
gapCounter = tempCounter; | |
} | |
tempCounter = 0; | |
} | |
} | |
if(mustCount) { | |
tempCounter++; | |
} | |
} | |
return gapCounter; | |
} | |
function decimalToBinary(N) { | |
var remainder = N % 2; | |
var quotient = Math.floor(N/2); | |
var result = "" + remainder; | |
do { | |
remainder = quotient % 2; | |
quotient = Math.floor(quotient/2); | |
result = remainder + result; | |
} while(quotient > 0); | |
return result; | |
} |
O que achou dele? Tem sugestões de como melhorá-lo? Caso não tenha entendido algo ou queira sugerir melhorias, escreva nos comentário desta postagem para que você possa me ajudar ou para que eu possa ajudá-lo. Abraço!
Comentários
Postar um comentário