Пытаюсь решить вопрос о двоичном разрыве кодильности, но мой код ужасен! ! !
Привет всем, я пытаюсь решить вопрос двоичного разрыва codility BinaryGap coding task - учитесь кодировать - Codility[^] но мое решение ужасно, и это вызовет у вас головную боль, но мне нужна помощь, чтобы заставить его работать.
My logic is (1) Convert integer N to binary format (2) Store binary format in a character array (3) Loop through character array starting from the left (the end of the character array) and discard any trailing '0s' till we find the first '1'. (4) If the next character after the first '1' is '0', count the number of '0s' till we find another '1'. (5) If there are still some characters in the array, repeat steps 3 and 4, else return the number of '0s' found as binary gap. This logic should work but putting into good concise Java code is my problem. Please my code is terrible and i couldn't complete it, please if it offends you, kindly forgive me, thanks for any help.
Что я уже пробовал:
public int solution(int N) { int currentGap = 0, largestGap = 0; int binaryGap = 0; // Convert integer to binary value String binaryString = Integer.toBinaryString(N); // Put binary value in a charater array char [] characters = binaryString.toCharArray(); // Run a loop starting from the left and check if the characters are 0 or 1 int j = 0; for(int i = characters.length - 1; i < characters.length; i--){ char c = characters[i]; // Disregard all trailing zeros till we get to the first 1 if(c == '1'){ j++; }else if(c == '0'){ // Needs to delete trailing zeros ? } } // I want to set currentGap to the number of zeros before getting to another 1 // then repeat the entire process above if there are still characters in the character array if(currentGap == largestGap){ return currentGap; }else if(currentGap < largestGap){ largestGap = binaryGap; } return binaryGap; }