Skip to content

Instantly share code, notes, and snippets.

@cpm586
Created March 20, 2016 20:57
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save cpm586/e86d300903215a938f0f to your computer and use it in GitHub Desktop.
Binary Gap
#include <stdio.h>
# define VALTEST 529
int nMayor(int number)
{
int aux=1, iter =0;
while(aux < number){
iter++;
aux = aux << 1;
//printf("\n%d, %d",iter, aux);
}
return iter;
}
int solucion(int number)
{
int band = 0;
int max0 = 0;
int bVal;
int count;
int bLenght = nMayor(number);
//printf("\n%d\n", bLenght);
while(bLenght--){
bVal = number & 3;
// printf("\n%d, %d, ", number, bVal);
if(bVal == 1){
//printf("c1, ");
band =1;
count = 0;
}
if((bVal==0 || bVal == 2) && band){
//printf("c0, ");
count++;
}
if(bVal == 2){
//printf("c10, ");
if(count > max0){
max0 = count;
//printf("max0= %d, ", max0);
}
band = 0;
}
number = number >> 1;
//printf("count= %d, ", count);
}
return max0;
}
int solucion2(int number)
{
int maxZeroes = 0;
int currentZeroes = 0;
bool isBetween = false;
int bLenght = nMayor(number);
while (bLenght--) {
if (!(number & 1)) {
if (isBetween) {
currentZeroes++;
}
} else {
if (isBetween && currentZeroes > maxZeroes) {
maxZeroes = currentZeroes;
}
currentZeroes = 0;
isBetween = true;
}
number = number>>1;
}
return maxZeroes;
}
int main()
{
printf("\nSOLUCION: %d: %d\n", VALTEST, solucion(VALTEST));
printf("\nSOLUCION2: %d: %d\n", VALTEST, solucion2(VALTEST));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment