Given a positive integer n
, find and return the longest distance between any two consecutive 1’s in the binary representation of n
. If there are less than two 1’s, return 0.
n
?Answer: n
is a positive integer which means 1 ≤ n ≤ 10^9
.
Answer: Using built-in functions for binary conversion is acceptable as it simplifies the problem.
n
to its binary representation.0
if there are fewer than two ‘1’s.#include <iostream>
#include <vector>
#include <bitset>
class Solution {
public:
int binaryGap(int n) {
// Convert the number to its binary representation
std::string binary = std::bitset<32>(n).to_string();
// Initialize the variables
int max_gap = 0;
int last_position = -1;
for (int i = 0; i < binary.size(); ++i) {
if (binary[i] == '1') {
if (last_position != -1) {
max_gap = std::max(max_gap, i - last_position);
}
last_position = i;
}
}
return max_gap;
}
};
int main() {
Solution solution;
int n = 22; // Example input
std::cout << "Binary Gap: " << solution.binaryGap(n) << std::endl;
return 0;
}
std::bitset<32>(n).to_string()
converts the integer n
to its binary representation in a string format.std::bitset<32>
always processes 32 bits, making the conversion O(1).Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?