前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >868. Binary Gap

868. Binary Gap

作者头像
Dylan Liu
发布2019-07-01 12:37:21
3930
发布2019-07-01 12:37:21
举报
文章被收录于专栏:dylanliudylanliu

Description

Difficulty:Easy Tag: Math

Given a positive integer N, find and return the longest distance between two consecutive 1's in the binary representation of N.

If there aren't two consecutive 1's, return 0.

Example 1:

代码语言:javascript
复制
Input: 22
Output: 2
Explanation: 
22 in binary is 0b10110.
In the binary representation of 22, there are three ones, and two consecutive pairs of 1's.
The first consecutive pair of 1's have distance 2.
The second consecutive pair of 1's have distance 1.
The answer is the largest of these two distances, which is 2.

Example 2:

代码语言:javascript
复制
Input: 5
Output: 2
Explanation: 
5 in binary is 0b101.

Example 3:

代码语言:javascript
复制
Input: 6
Output: 1
Explanation: 
6 in binary is 0b110.

Example 4:

代码语言:javascript
复制
Input: 8
Output: 0
Explanation: 
8 in binary is 0b1000.
There aren't any consecutive pairs of 1's in the binary representation of 8, so we return 0.

Note:

1 <= N <= 10^9

Solution

其实是一道数1的题,用 two pointers 解决

代码语言:javascript
复制
func binaryGap(N int) int {
    max,pre,next := 0,0,1
    for  ;N & 1 == 0 && N > 0; pre,N = pre+1, N >> 1{
    }
    
    for next,N = pre + 1,N>>1;N > 0; N>>=1 {
        for N & 1 == 0{
            next++
            N >>=1
        }
        if next -pre > max {
            max = next - pre
        }
        pre = next
        next += 1
    }
    
    return max
}

网友有一个更精妙简单的解法

代码语言:javascript
复制
public int binaryGap(int N) {
        int res = 0;
        for (int d = -32; N > 0; N /= 2, d++)
            if (N % 2 == 1) {
                res = Math.max(res, d);
                d = 0;
            }
        return res;
    }

d 是两个1之间距离,碰到1之后d置0.

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Solution
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档