Codility-BinaryGap

本文介绍了一种算法来寻找一个正整数二进制表示中由1包围的最大连续0序列长度。通过逐步去除最低位直到遇到1开始计数,并在遇到下个1时记录最长序列。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

A binary gap within a positive integer N is any maximal sequence of consecutive zeros that is surrounded by ones at both ends in the binary representation of N.

For example, number 9 has binary representation 1001 and contains a binary gap of length 2. The number 529 has binary representation 1000010001 and contains two binary gaps: one of length 4 and one of length 3. The number 20 has binary representation 10100 and contains one binary gap of length 1. The number 15 has binary representation 1111 and has no binary gaps.

依据除2取余法为思路。

1.先除2至第一个为1的位置。

2.统计至下一个为1位置中间0的个数。

3.比较,取个数最多的结果。

classSolution {
    publicint solution(int N){
        // write your code in C# 6.0 with .NET 4.5 (Mono)
        int Temp=0,Max=0;
        for(;N%2!=1;N/=2){}
        for(;N!=1;N/=2)
        {
            if(N%2==1){Temp=0;}
            else{Temp++;}
            if(Temp>Max){Max=Temp;}
        }
        return Max;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值