java编程题2
发布网友
发布时间:2022-05-27 11:01
我来回答
共2个回答
热心网友
时间:2023-10-18 04:22
public class BinaryChange
{
/**
* @param args
*/
public static void main(String[] args)
{
// TODO Auto-generated method stub
Scanner in=new Scanner(System.in);
long num=in.nextLong();
BinaryChange bc=new BinaryChange();
System.out.print("binary:");
bc.print(bc.toBinary(num));
System.out.println("");
System.out.println("maxLengthOfOne:"+bc.maxLengthOfOne(num));
System.out.println("maxLengthOfZero:"+bc.maxLengthOfZero(num));
}
public int[] toBinary(long num){
int[] bin=new int[32];
for (int i = 31; i > 0 && num>0; i--)
{
bin[i]=(int) (num%2);
num /=2;
}
return bin;
}
public int maxLengthOfOne(long num){
int[] bin=toBinary(num);
boolean start=false;
int max=0,second=0;
for (int i = 0; i < bin.length; i++)
{
if (start)
{
if(bin[i]==1)
{
second ++;
}else {
max = max > second ? max : second;
second = 0;
}
}
else if(bin[i]==1)
{
start=true;
i--;
}
}
return max > second ? max : second;
}
public int maxLengthOfZero(long num){
int[] bin=toBinary(num);
boolean start=false;
int max=0,second=0;
for (int i = 0; i < bin.length; i++)
{
if (start)
{
if(bin[i]==0)
{
second ++;
}else {
max = max > second ? max : second;
second = 0;
}
}
else if(bin[i]==1)
{
start=true;
i--;
}
}
return max > second ? max : second;
}
public void print(int[] a){
boolean start=false;
for (int i = 0; i < a.length; i++)
{
if (start)
{
System.out.print(a[i]);
}
else if(a[i]==1)
{
start=true;
i--;
}
}
}
}
热心网友
时间:2023-10-18 04:22
直接拿作业题提问,,不合适吧。。