Store the binary representaiton and then find the max distance betweeb location of 1’s.
Code
class Solution {
public:
int binaryGap(int n) {
deque<char> s;
while(n > 0) {
if(n % 2 == 1) s.push_front('1');
else s.push_front('0');
n /= 2;
}
vector<int> idx;
for(int i = 0 ; i < s.size() ; ++i) if(s[i] == '1') idx.push_back(i);
if(idx.size() <= 1) return 0;
int maxWidth = 1;
for(int i = 1 ; i < idx.size() ; ++i) maxWidth = max(maxWidth, idx[i] - idx[i-1]);
return maxWidth;
}
};