翻转数位

https://leetcode-cn.com/problems/reverse-bits-lcci/

 

面试题 05.03. 翻转数位

给定一个32位整数 num,你可以将一个数位从0变为1。请编写一个程序,找出你能够获得的最长的一串1的长度。

示例 1:

输入: num = 1775(110111011112)
输出: 8

示例 2:

输入: num = 7(01112)
输出: 4




class Solution {
public:
    // 到x为止,最长的长度
    int reverseBits(int num) {
        int this_ = 0;
        int insert = 0;
        int res = 0;
        for(int i=0; i<32; i++){
            bool this_bit = num & 1;
            num = num>>1;
            if(this_bit==1){
                this_ ++;
                insert ++;
            }
            else{
                insert = this_ + 1;
                this_ = 0;
            }
            res = max(insert, res);

        }

        return res;

    }
};

 

posted @ 2021-06-30 21:56  会飞的雅蠛蝶  阅读(77)  评论(0编辑  收藏  举报