Java:判断二进制中左侧起始有多少个0
发布网友
发布时间:2022-10-12 13:08
我来回答
共1个回答
热心网友
时间:2023-10-22 03:41
您好,这样的:
public class Test {
public static void main(String args[]) {
int pow = 5;
for(byte i = 0;i < (int)Math.pow(2, pow);i ++)
{
//8 is 1000, so we use (i&8) to know if the most left is 1 or 0
if((i & (int)Math.pow(2, pow - 1)) > 0)
{
System.out.println("Left of Binary " + i + " is " + 1);
}
else
{
System.out.println("Left of Binary " + i + " is " + 0);
}
}
}
}
-----------------------------------------------
class test{
public static void main(String[] args) {
System.out.println(f("10000111110010000111111011111"));
}
static int f(String str) {
int max = 1;
int fast = 0;
char fastC =str.charAt(0);
for (int i = 1; i < str.length(); i++) {
if(str.charAt(i)!=fastC) {
fastC=str.charAt(i);
if (max<i-fast) {
max = i-fast;
}
fast=i;
}
}
//最后一组连续串
if(max<str.length()-fast) {
max = str.length()-fast;
}
return max;
}
}