Find the Longest Sequence of Zeros in the Binary Representation of an IntegerThe problem is to transform an integer and represent it as a sequence of binary digits and then to determine the most significant sequence of zeros that one's enclose. In other words, if the binary representation string does not contain any zeros placed between ones, the result should be 0. Furthermore, zero suffixes of a binary number should not be taken if they are not bounded by one. In binary form, the numeral 9 equals 1001. The length of the most extended sequence of zeros is 00, so the binary gap is 2. So, the number 20 in the binary form will be 10100. The most extended sequence of zeros is 0, so the binary gap is 1. Approach-1
Let's implement the above approach in a Java program. File Name: LongestBinaryGap.java Output: The longest binary gap for 529 is: 4 Time Complexity: Incidentally, the algorithm also has the time complexity of O(log n) because after converting the integer into binary format, the algorithm only moves through the binary string or the number of digits, which is equivalent to log n. Space Complexity: The space complexity is O(log n), for the most part, due to storing the binary form of an integer, which will be of size approximately log n. Approach-2
Let's implement the above approach in a Java program. File Name: LongestBinaryGap.java Output: The longest binary gap for 529 is: 4 Time Complexity: The time complexity of the solution is log(n). Here, each bit of an integer takes some number of steps, and their number is proportional to the number of bits present in the integer. Space Complexity: The space complexity is O(1) since the program creates only several integer Variables irrespective of the size of the input. ConclusionThe first solution based on using string manipulation provides a conventional, obvious solution with the complexity of space O(log n), but it is still sufficient. However, the above bitwise does not require the storage of the entire binary string and has O(1) space complexity by operating on each bit only. Both of them belong to the O(log n) time complexity, but the first method requires less amount of space, and in environments where space is a constraint, then the second method is preferable. |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India