计算二进制数中的连续1

时间:2016-06-03 03:07:44

标签: java

import java.util.Scanner;
import java.util.Arrays;
class Solve
{
  public static void main(String args[])
  {
    Scanner in = new Scanner(System.in);
    int i=0,count=0;
    int[] arr = new int[10];
    int n =in.nextInt();
    while(n!=0)
    {
      arr[i]=n%2;
      i++;
      n=n/2;
    }
    System.out.println(Arrays.toString(arr));
  }

  }
}

我只想计算连续1的数量。 ?像1110011001会给我回答5 ..我该怎么办?

10 个答案:

答案 0 :(得分:2)

System.out.println(Integer.toBinaryString(n).replaceAll("(0|(?<!1)1(?!1))", "").length());

正则表达式意味着:替换所有0&#39;以及任何1之前或之后不是1

答案 1 :(得分:0)

您可以将其作为字符串[编辑为所有连续的1&#39;]进行处理:

String binary = in.nextLine();
String[] arrayBin = binary.split("0+"); // an array of strings without 0's

int result=0;

for (int i=0; i < arrayBin.length; i++){
if (arrayBin[i].length()<2){
result+=0;
}
else {
result+=arrayBin[i].length();
}
}
System.out.println("Total consecutive = "+result);

答案 2 :(得分:0)

我们可以在最不重要的位置识别两个连续的二进制位,如下所示:

(value & 0b11) == 0b11

我们可以将值向右移动,如下所示:

value >>>= 1;

重要的是使用tripple >>>而不是>>,因为我们不关心符号位。

然后,我们所要做的就是跟踪连续1的数量:

int count(int value) {
    int count = 1;
    int total = 0;
    while (value != 0) {
        if ((value & 0b11) == 0b11) {
            count++;
        } else {
            if (count > 1) {
                total += count;
            }
            count = 1;
        }
        value >>>= 1;
    }
    return total;
}

测试用例:

assertEquals(0, count(0b0));
assertEquals(0, count(0b1));
assertEquals(0, count(0b10));
assertEquals(2, count(0b11));
assertEquals(5, count(0b1110011));
assertEquals(5, count(0b1100111));
assertEquals(6, count(0b1110111));
assertEquals(7, count(0b1111111));
assertEquals(32, count(-1));

如果你只想要最大长度,我有一个类似的答案:https://stackoverflow.com/a/42609478/360211

答案 3 :(得分:0)

你可以利用Brian Kernighan的算法来计算最高连续数1。 java伪代码就是这样的

    // Initialize result
    int count = 0;

    // Count the number of iterations to
    // reach n = 0.
    while (n!=0)
    {
        // This operation reduces length
        // of every sequence of 1s by one.
        n = (n & (n << 1));
        count++;
    }

答案 4 :(得分:0)

    public class Solution {
public int findMaxConsecutiveOnes(int[] nums) {
    if(nums == null || nums.length == 0){
        return 0;
    }
    int counter = 0, max = Integer.MIN_VALUE;
    for(int i = 0; i < nums.length; i++){
        if(nums[i] == 1){
            counter += nums[i];
        } else{
            counter = nums[i];
        }
        max = Math.max(counter, max);
    }
    return max;
}

}

答案 5 :(得分:0)

对于这个问题,我们可以在一些Java操作员的帮助下使用一个技巧。     &运算符,以及Java中的左移(<<)。

代码段将类似于:

public getConsecutiveCount(int inputNumber)
{
  int count = 0 ;
  while(inputNumber != 0)
  {
     inputNumber = inputNumber & (inputNumber << 1);
   count++;
  }
}

说明:

此功能正在接受输入(例如:我们要检查有多少      连续1的整数6以二进制表示)

因此,输入号码将类似于:

 inputNumber = ((110) & ((110)<<1))    {This left shift will result in 100  so final op :
                                        110 & 100 which 100 , every time '0' is added to 
                                        our result and we iterate until whole number will 
                                        be zero and value of our count variable will be 
                                        our expected outcome }

答案 6 :(得分:0)

以二进制(例如101)查找最大连续1

int n = Convert.ToInt32(Console.ReadLine());
string[] base2=Convert.ToString(n,2).Split('0');

int count=0;

foreach(string s in base2)
    count=s.Length>count?s.Length:count;


Console.WriteLine(count);

答案 7 :(得分:-1)

public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    int n = in.nextInt();
    String bs = Integer.toBinaryString(n);// bs=Binary String
    char[] characters = bs.toCharArray();
    int max = 1;
    int temp = 1;

    for (int i = 0; i < characters.length - 1; i++) {
        if (characters[i] == characters[i + 1] & characters[i] == '1' & characters[i + 1] == '1') {
            temp++;
            if (temp > max) {
                max = temp;
            }
        } else {
            temp = 1;
        }

    }
    System.out.println(max);
}

答案 8 :(得分:-1)

/ *给定十进制数字打印二进制转换后连续1的最大数量* /

import java.io.*;
import java.util.*;

public class Solution {

    public void countBinaryOne(int num){
        int var =0, countOne= 0, maxCt=0;
        while(num>0){
            var= num%2;    
                if(var==1){
                    countOne=countOne+1;
                }else{
                    if(maxCt<countOne){    
                        maxCt= countOne;    
                        countOne=0;
                    }else{
                        countOne=0;
                }
            }

            num=num/2;          
        }
        System.out.println(Math.max(countOne,maxCt));

    }

    public static void main(String[] args) {
        Scanner in= new Scanner(System.in);
        int n= in.nextInt();
        Solution sol= new Solution();
        sol.countBinaryOne(n);
    }
}

答案 9 :(得分:-1)

public static void digitBinaryCountIfOne(int n){

    int reminder=0, sum=0, total = 0;

    while(n>0)
        {
        reminder = n%2;
        n/=2;
            if(reminder==1){
            sum++;
                if(sum>=total)
                    total=sum;


            }else{
                sum=0;
                }   

        } 
        System.out.println(total);
}