java - Max Zero Binary Gap colidity practice test StringOutOfBounds Exception -


this colidity binary gap problem. restrictions o(logn) runtime , o(1) space complexity.

write function:

class solution { public int solution(int n); }

that, given positive integer n, returns length of longest binary gap. function should return 0 if n doesn't contain binary gap.

for example, given n = 1041 function should return 5, because n has binary representation 10000010001 , longest binary gap of length 5.

i liked trying go solution , wondering if there way ignore out of bounds exception. tried try catch didn't work. there way out of or have different approach? here code:

import java.util.*;  // can write stdout debugging purposes, e.g. // system.out.println("this debug message");  class solution {     public int solution(int n) {          int maxzero = 0;         int j =0;         int tempzero=0;          //convert number binary         string b = integer.tobinarystring(n);         boolean zeroflag = false;          //iterate on char array , check zeros         for(int = 0; < b.length(); i++){              = j;              //activate flag , check gap             if(b.charat(i) == '1' && b.charat(i+1) == '0'){                 zeroflag = true;                 //reset temp                 tempzero = 0;                 j++;                  //a bit string never start 0 can never stuck                 while(zeroflag == true && b.charat(j) != '1'){                     j++;                     tempzero++;                     if(b.charat(j) == '1'){                         break;                     }                 }                  //reset zeroflag                 zeroflag == false;                  //compare temp , max find new max                    if(tempzero > maxzero){                     maxzero = tempzero;                 }             }         }          //now return max 0         return maxzero;     } } 


Comments

Popular posts from this blog

ios - MKAnnotationView layer is not of expected type: MKLayer -

ZeroMQ on Windows, with Qt Creator -

unity3d - Unity SceneManager.LoadScene quits application -