Binary Gap - Math - Easy - LeetCode
💻 coding

Binary Gap - Math - Easy - LeetCode

1 min read 289 words
1 min read
ShareWhatsAppPost on X
  • 1The task is to find the longest distance between adjacent 1's in the binary representation of a positive integer n.
  • 2If there are no adjacent 1's, the function should return 0.
  • 3The provided algorithm operates with a time complexity of O(n) and a space complexity of O(1).

AI-generated summary · May not capture all nuances

Key Insight
AskGif

"The task is to find the longest distance between adjacent 1's in the binary representation of a positive integer n."

Binary Gap - Math - Easy - LeetCode

Given a positive integer n, find and return the longest distance between any two adjacent 1's in the binary representation of n. If there are no two adjacent 1's, return 0.

Two 1's are adjacent if there are only 0's separating them (possibly no 0's). The distance between two 1's is the absolute difference between their bit positions. For example, the two 1's in "1001" have a distance of 3.

Example 1:

Input: n = 22 Output: 2 Explanation: 22 in binary is "10110". The first adjacent pair of 1's is "10110" with a distance of 2. The second adjacent pair of 1's is "10110" with a distance of 1. The answer is the largest of these two distances, which is 2. Note that "10110" is not a valid pair since there is a 1 separating the two 1's underlined. Example 2:

Input: n = 5 Output: 2 Explanation: 5 in binary is "101". Example 3:

Input: n = 6 Output: 1 Explanation: 6 in binary is "110". Example 4:

Input: n = 8 Output: 0 Explanation: 8 in binary is "1000". There aren't any adjacent pairs of 1's in the binary representation of 8, so we return 0. Example 5:

Input: n = 1 Output: 0

Constraints:

1 <= n <= 109

public class Solution {
 public int BinaryGap(int n) {
 int res = 0, tmp = 1;
 bool flag = false;
 while (n != 0) {
 if(n % 2 != 0 && !flag) flag = true;
 else if (n % 2 != 0 && flag) {
 res = Math.Max(tmp, res);
 tmp = 1;
 } else if(n % 2 == 0 && flag) tmp++;
 n /= 2;
 }
 return res;
 }
}

Time Complexity: O(n)

Space Complexity: O(1)

Enjoyed this article?

Share it with someone who'd find it useful.

ShareWhatsAppPost on X

sumitc91

Published on 1 October 2020 · 1 min read · 289 words

Part of AskGif Blog · coding

You might also like

Binary Gap - Math - Easy - LeetCode | AskGif Blog