A binary gap is a run of consecutive zeros in the binary representation of a positive integer that is surrounded by a one on both sides. Given an integer, return the length of its longest binary gap.

Trailing zeros do not count because they have no one after them. Return 0 when the number has no binary gap, and also when the input is null or less than 1.

Examples:

Input: n = 9 Output: 2 Explanation: 9 is 1001 in binary, which has one gap of length 2 Input: n = 529 Output: 4 Explanation: 529 is 1000010001 in binary, with gaps of length 4 and 3 Input: n = 20 Output: 1 Explanation: 20 is 10100 in binary; the trailing zeros are ignored so the answer is 1 Input: n = 15 Output: 0 Explanation: 15 is 1111 in binary and contains no zeros at all Input: n = null Output: 0 Explanation: Null input returns 0
Apex Code Editor

Welcome to Lightning Challenge!

How It Works

  • • Write your solution in the code editor
  • • Connect your Salesforce org to test
  • • Submit to check if your solution passes
  • • Use hints if you get stuck

Contest Alert

🏆 #CodeEveryDay November 2026 (Nov 16–30)Sponsored by FLXBL

Contest runs November 16 - 30. Complete challenges to climb the leaderboard!

Prizes 1 & 2: Salesforce certification exam voucher — won by random drawing, where every point is a ticket. see all prizes

Only the 15 daily challenges shown during this contest count toward points. Earlier dailies don't carry over.

Wally can't hear you

Please sign in to access the AI Assistant

Sign In