Leetcode 868 二进制间距
每日一题 Day2
题目描述
Given a positive integer n, find and return the longest distance between any two adjacent 1's in the binary representation of n. If there are no two adjacent 1's, return 0.
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/binary-gap
先把一个数字换成二进制,然后直接求就完了。
时间 \(O(\log n)\), 空间 \(O(1)\)
class Solution {
public:
int binaryGap(int n) {
int lst = -1, now = 0, ans = 0;
while (n) {
if (n & 1) {
if (~lst) ans = std::max(now - lst, ans);
lst = now;
}
n >>= 1, now++;
} return ans;
}
};
希望我们都有一个光明的未来

浙公网安备 33010602011771号