868. Binary Gap
/**
* Problem: LeetCode 868 - Binary Gap
* Difficulty: Easy
* Language: Java
* Author: CodeByTushu
*/
class Solution {
public int binaryGap(int n) {
int lastPos = -1;
int maxGap = 0;
int currPos = 0;
while (n > 0) {
if ((n & 1) == 1) {
if (lastPos != -1) {
maxGap = Math.max(maxGap, currPos - lastPos);
}
lastPos = currPos;
}
n >>= 1;
currPos++;
}
return maxGap;
}
}
"""
Problem: LeetCode 868 - Binary Gap
Difficulty: Easy
Language: Python
Author: CodeByTushu
"""
class Solution:
def binaryGap(self, n: int) -> int:
last_pos = -1
max_gap = 0
curr_pos = 0
while n > 0:
if n & 1:
if last_pos != -1:
max_gap = max(max_gap, curr_pos - last_pos)
last_pos = curr_pos
n >>= 1
curr_pos += 1
return max_gap
/**
* Problem: LeetCode 868 - Binary Gap
* Difficulty: Easy
* Language: C++
* Author: CodeByTushu
*/
#include <algorithm>
using namespace std;
class Solution {
public:
int binaryGap(int n) {
int lastPos = -1;
int maxGap = 0;
int currPos = 0;
while (n > 0) {
if (n & 1) {
if (lastPos != -1) {
maxGap = max(maxGap, currPos - lastPos);
}
lastPos = currPos;
}
n >>= 1;
currPos++;
}
return maxGap;
}
};
/**
* Problem: LeetCode 868 - Binary Gap
* Difficulty: Easy
* Language: JavaScript
* Author: CodeByTushu
*/
/**
* @param {number} n
* @return {number}
*/
var binaryGap = function(n) {
let lastPos = -1;
let maxGap = 0;
let currPos = 0;
while (n > 0) {
if ((n & 1) === 1) {
if (lastPos !== -1) {
maxGap = Math.max(maxGap, currPos - lastPos);
}
lastPos = currPos;
}
n >>>= 1;
currPos++;
}
return maxGap;
};