二进制间距:
给定一个正整数 n,找到并返回 n 的二进制表示中两个 相邻 1 之间的 最长距离 。如果不存在两个相邻的 1,返回 0 。
如果只有 0 将两个 1 分隔开(可能不存在 0 ),则认为这两个 1 彼此 相邻 。两个 1 之间的距离是它们的二进制表示中位置的绝对差。例如,“1001” 中的两个 1 的距离为 3 。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/binary-gap
输入:n = 22
输出:2
解释:22 的二进制是 “10110” 。
在 22 的二进制表示中,有三个 1,组成两对相邻的 1 。
第一对相邻的 1 中,两个 1 之间的距离为 2 。
第二对相邻的 1 中,两个 1 之间的距离为 1 。
答案取两个距离之中最大的,也就是 2 。
public class BinaryGap {
public static int binaryGap(int n) {
int max = 0,num = 0;
boolean flag = false;
while (n!=0){
if (1 == n%2){
flag = true;
}
if (flag){
if (1 == n%2){
max = Math.max(max,num);
num = 0;
}
n = n>>1;
num ++;
} else {
n = n>>1;
}
}
return max;
}
public static void main(String[] args) {
System.out.printf(binaryGap(22)+"");
}
}