difficult:easy #868
Given a positive integer N, find and return the longest distance between two consecutive 1’s in the binary representation of N.
If there aren’t two consecutive 1’s, return 0.
Example 1:
Input: 22
Output: 2
Explanation:
22 in binary is 0b10110.
In the binary representation of 22, there are three ones, and two consecutive pairs of 1’s.
The first consecutive pair of 1’s have distance 2.
The second consecutive pair of 1’s have distance 1.
The answer is the largest of these two distances, which is 2.
Example 2:
Input: 5
Output: 2
Explanation:
5 in binary is 0b101.
Example 3:
Input: 6
Output: 1
Explanation:
6 in binary is 0b110.
Example 4:
Input: 8
Output: 0
Explanation:
8 in binary is 0b1000.
There aren’t any consecutive pairs of 1’s in the binary representation of 8, so we return 0.
Note:1 <= N <= 10^9
解法一:
#include<vector>
int binaryGap(int N) {
int distance = 0;
std::vector<int> index;
for (int i = 1; N != 0;i++) {
if (N % 2 != 0)
index.push_back(i);
N = N >> 1;
}
for(int i = 0;i < index.size()-1;i++){
int max = index[i + 1] - index[i];
if (max > distance)
distance = max;
}
return distance;
}
解法二:
int binaryGap(int N) {
int last = -1,distance = 0;
for (int i = 1; N != 0; i++) {
if (N % 2 != 0) {
if (last > 0)
distance = (i - last) > distance ? (i - last) : distance;
last = i;
}
N = N >> 1;
}
return distance;
}
版权声明:原创,转载请注明来源,否则律师函警告
本博客所有文章除特别声明外,均采用 CC BY-SA 3.0协议 。转载请注明出处!