Skip to content

Latest commit

 

History

History
45 lines (39 loc) · 730 Bytes

868.二进制间距.md

File metadata and controls

45 lines (39 loc) · 730 Bytes

868.二进制间距

/*
 * @lc app=leetcode.cn id=868 lang=typescript
 *
 * [868] 二进制间距
 */

// @lc code=start
function binaryGap(n: number): number {}
// @lc code=end

解法 1: lowbit

function binaryGap(n: number): number {
  if (!n) return 0
  let pre = -1,
    res = 0
  for (let i = 0; i < 32; i++) {
    if (n & (1 << i)) {
      if (pre === -1) pre = i
      else {
        res = Math.max(res, i - pre)
        pre = i
      }
    }
  }
  return res
}

Case

test.each([
  { input: { n: 22 }, output: 2 },
  { input: { n: 8 }, output: 0 },
  { input: { n: 5 }, output: 2 },
])('input: n = $input.n', ({ input: { n }, output }) => {
  expect(binaryGap(n)).toEqual(output)
})