Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit 303d327

Browse files
Diego Flores CastilloDiego Flores Castillo
Diego Flores Castillo
authored and
Diego Flores Castillo
committed
binary_gap-002 (feature): implement binary gap with three loops
1 parent 6b57c22 commit 303d327

File tree

2 files changed

+35
-19
lines changed

2 files changed

+35
-19
lines changed

.idea/codeStyles/Project.xml

Lines changed: 3 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

LeetcodeProblems/Algorithms/Binary_Gap.js

Lines changed: 32 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ Example 1:
1111
Input: 22
1212
Output: 2
1313
Explanation:
14-
22 in binary is 0b10110.
14+
22 in binary is 10110.
1515
In the binary representation of 22, there are three ones, and two consecutive pairs of 1's.
1616
The first consecutive pair of 1's have distance 2.
1717
The second consecutive pair of 1's have distance 1.
@@ -21,42 +21,55 @@ Example 2:
2121
Input: 5
2222
Output: 2
2323
Explanation:
24-
5 in binary is 0b101.
24+
5 in binary is 0101.
2525
Example 3:
2626
2727
Input: 6
2828
Output: 1
2929
Explanation:
30-
6 in binary is 0b110.
30+
6 in binary is 0110.
3131
Example 4:
3232
3333
Input: 8
3434
Output: 0
3535
Explanation:
36-
8 in binary is 0b1000.
36+
8 in binary is 01000.
3737
There aren't any consecutive pairs of 1's in the binary representation of 8, so we return 0.
3838
*/
3939

4040
/**
4141
* @param {number} N
4242
* @return {number}
4343
*/
44-
var binaryGap = function (N) {
45-
var maxDist = 0;
46-
var currentDist = 0;
47-
while (N > 0) {
48-
const bit = N % 2;
49-
N >>= 1;
50-
if (bit === 1) {
51-
currentDist = 1;
52-
while (N > 0 && N % 2 === 0) {
53-
currentDist++;
54-
N >>= 1;
55-
}
56-
if (N !== 0 && currentDist > maxDist) maxDist = currentDist;
44+
45+
const binaryGap = (n) => {
46+
let decimalNumber = n;
47+
let binaryNumber = "";
48+
while (decimalNumber !== 0) {
49+
let result = decimalNumber % 2;
50+
if (result === 0) {
51+
decimalNumber = decimalNumber / 2;
52+
binaryNumber = result.toString() + binaryNumber;
53+
}
54+
if (result === 1) {
55+
decimalNumber = (decimalNumber - 1) / 2;
56+
binaryNumber = result.toString() + binaryNumber;
57+
}
58+
}
59+
let positionsWithOne = [];
60+
for (let i = 0; i < binaryNumber.length; i++) {
61+
if (binaryNumber[i] === "1") {
62+
positionsWithOne.push(i);
5763
}
5864
}
59-
return maxDist;
60-
};
6165

66+
let distance = 0;
67+
for (let j = 0; j < positionsWithOne.length - 1; j++) {
68+
distance =
69+
distance <= positionsWithOne[j + 1] - positionsWithOne[j]
70+
? positionsWithOne[j + 1] - positionsWithOne[j]
71+
: distance;
72+
}
73+
return distance;
74+
};
6275
module.exports.binaryGap = binaryGap;

0 commit comments

Comments
 (0)