• 刷题-力扣-面试题 05.03. 翻转数位


    面试题 05.03. 翻转数位

    题目链接

    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/reverse-bits-lcci
    著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

    题目描述

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

    示例 1:

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

    示例 2:

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

    题目分析

    1. 根据题目描述计算32位整数中将其中一位0换成1后,1的个数
    2. 设置两个指针front和rear,front顺序遍历bits,rear指向连续1的第一位,始终保证rear和front之间只有0个或1个1

    代码

    class Solution {
    public:
        int reverseBits(int num) {
            if (num == 0) { return 1; }
            bitset<32> bits(num);
            int rear = 0;
            int front = 0;
            int maxOneLen = 0;
            int midOne = 0;
            bool hasZero = false;
            while (front < 32) {
                if (bits[front] == 0) {
                    if (hasZero) {
                        maxOneLen = max(maxOneLen, front - rear);
                        rear = midOne + 1;
                        midOne = front;
                    } else {
                        hasZero = true;
                        midOne = front;
                    }
                }
                ++front;
            }
            maxOneLen = max(maxOneLen, front - rear);
            return maxOneLen;
        }
    };
    
  • 相关阅读:
    ZOJ 3818 Pretty Poem
    HDU 4597 Play Game
    HDU 4497 GCD and LCM
    CSU 1335 高桥和低桥
    UVA 10791 Minimum Sum LCM
    CSU 1119 Collecting Coins
    CSU 1120 病毒
    UVA 12169 Disgruntled Judge
    HDU 1301 Jungle Roads
    POJ 1258 Agri-Net
  • 原文地址:https://www.cnblogs.com/HanYG/p/15262992.html
Copyright © 2020-2023  润新知