@SomeBottleLeetcode每日一题 —— 868. 二进制间距 中发帖

思路
简单题,逐位扫描,遇到 1 时根据距离上一个 1 的长度更新状态即可。
代码
class Solution {
public:
int binaryGap(int n) {
int res=0;
int start=-1;
int pos=0;
while(n>0){
if((n&1)==1){
if(start>=0)
res=max(res,pos-start);
start=pos;
}
n>>=1;
pos++;
}
return res;
}
};