题解 | #求最大连续bit数#

求最大连续bit数

https://www.nowcoder.com/practice/4b1658fd8ffb4217bc3b7e85a38cfaf2

#include <iostream>
using namespace std;

//统计最大连续bit数
int count(const int n) {
    //用于计数
    int c = 0;
    //用于存储结果
    int result = 0;
    //用除二的方式得到其二进制的每一位
    for (int i = n; i > 0; i /= 2) {
        //遇到1,计数一次
        if (i % 2 == 1) {
            c++;
        }
        //遇到0,计数归0
        else {
            c = 0;
        }
        //计数超过上一个结果记录,更新结果
        if (c > result) {
            result = c;
        }
    }
    return result;
}

int main() {
    int a;
    while (cin >> a) { // 注意 while 处理多个 case
        cout << count(a) << endl;
    }
}
// 64 位输出请用 printf("%lld")

全部评论

相关推荐

09-17 10:53
四川大学 C++
牛客91242815...:会写标书没有任何卵用,鉴定为横向垃圾导师的受害者
点赞 评论 收藏
分享
投递北京经纬恒润科技股份有限公司等公司10个岗位
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务