面试题 05.03. 翻转数位-----位运算

题目表述

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

示例:

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

位运算

双指针,利用与计算出num的0的位置,计算3个0间的位置差距,求出来最长序列即可。

class Solution { public int reverseBits(int num) { int res = 0; int count = 0; int left = 0; int pre = -1; int fast = 0; for(;fast < 32; fast++){ int tmp = num & (1<<fast); if(tmp == 0){ if(count == 0){ left = fast; count++; continue; } res = Math.max(res, fast - pre -1); pre = left; left = fast; count++; } } res = Math.max(res, fast - pre -1); return res; } }
class Solution { public int reverseBits(int num) { int cur = 0; int insert = 0; int res = 1; for(int i = 0; i < 32; i++){ if((num & (1 << i)) != 0){ cur += 1; insert += 1; }else{ insert = cur + 1; cur = 0; } res = Math.max(res , insert); } return res; } }

__EOF__

本文作者Younger
本文链接https://www.cnblogs.com/youngerwb/p/16286696.html
关于博主:评论和私信会在第一时间回复。或者直接私信我。
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!
声援博主:如果您觉得文章对您有帮助,可以点击文章右下角推荐一下。您的鼓励是博主的最大动力!
posted @   YoungerWb  阅读(28)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
点击右上角即可分享
微信分享提示