找到连续的1的数字

时间:2018-01-03 23:09:43

标签: java arrays

我试图在二进制文件中找到连续1的数字。

示例:将十进制数转换为二进制数并找到连续的1

public void startGeo(View view) {
    isRunning = true;
    ha.postDelayed(new Runnable() {

        @Override
        public void run() {

            StringRequest request = new StringRequest(Request.Method.POST, insertURL, new com.android.volley.Response.Listener<String>() {
                @Override
                public void onResponse(String response) {

                }
            }, new com.android.volley.Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {

                }
            }) {
                @Override
                protected Map<String, String> getParams() throws AuthFailureError {
                    Map<String, String> parameters = new HashMap<String, String>();
                    parameters.put("latitude", t_latitude.getText().toString());
                    parameters.put("longitude", t_longitude.getText().toString());


                    return parameters;

                }
                protected void sendLocationDataToWebsite(Location location) {
                    DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    dateFormat.setTimeZone(TimeZone.getDefault());
                    Date date = new Date(location.getTime());
                    Map<String, String> parameters = new HashMap<String, String>();
                    parameters.put("date", URLEncoder.encode(dateFormat.format(date), "UTF-8");

                }
            };
            requestQueue.add(request);
            Toast.makeText(MapActivity.this, "Enviado", LENGTH_LONG).show();

            if (isRunning) {
                ha.postDelayed(this, 10000);
            }
        }
    }, 10000);
}

我总是得到0.似乎条件在我的代码中不起作用。你能否提出你对我在哪里出错的建议?

5 个答案:

答案 0 :(得分:2)

你的问题不是那么清楚,但你的算法中的AFAIU,你试图找到最重复的1的数量。问题是当你进行比较if (arr[i] == index)时,比较是用char和整数完成的,因为arr的类型是char数组。不是吗?要克服它,您可以将char array转换为整数或将整数index值转换为char。我这样做是为了克服它。

if (arr[i] == index + '0')

这不是一个非常优雅的解决方案。我假设你是一名学生,并希望你表明错误。如果我想做这样的事情,我会用,

private static int maxConsecutiveOnes(int x) {
        // Initialize result
        int count = 0;

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

            count++;
        }

        return count;
}

它的诀窍是,

      11101111   (x)
    & 11011110   (x << 1)
    ----------
      11001110   (x & (x << 1)) 
        ^    ^
        |    |
   trailing 1 removed

答案 1 :(得分:1)

根据我的理解,您希望计算post_render值的二进制表示中1组的最大长度。例如。 int结果将为7917=0b1111011101101(我们有以下4组:1,2,3,4。

您可以使用位操作(并避免字符串转换)。您有一个计数器(计算当前组中1的数量)和1,其中包含所有此类金额的最大值。您只需检查max的最低位,然后向右旋转值,直到它变为1,如0

或者只是以一种非常简单的方式进行操作 - 将其转换为二进制字符串并计算其中getMaxConsecutiveSetBit1个字符的数量,例如1。还有一个计数器+最大值。不要忘记,Java中的getMaxConsecutiveSetBit2是JVM级别的char。因此,将intcharint进行比较时,您没有编译问题,但这是错误的。要检查字符是否为1,您必须使用字符 - 1

'1'

答案 2 :(得分:1)

index变量的类型从int更改为char

static char index = 1;

让这一行进行比较:

if (arr[i] == index)

做好自己的工作。将int 1(在您的代码中,这是index变量中存储的值)与char '1'(在您的示例中,它是arr[]的当前已检查元素)进行比较,检查给定的ASCII代码char等于int值1.此比较永远不会为真,因为char'1'具有ASCII码49,这是与值1进行比较的值(49永远不等于到1)。

您可能需要查看网络中的ASCII代码表,以查看其中的所有字符都已分配了相应的数字值。您需要注意,在将charint==操作系统进行比较时,会考虑这些值。

当您将上述类型的index更改为char时,比较工作正常,您的代码似乎已修复。

答案 3 :(得分:0)

使用for循环结构并更改一些内容,同时添加一些其他统计数据来报告哪些内容可能有用。我计算数字中1的总数,连续1的数量(1的组)和连续1的最大数量。你的for循环也是基于字符串长度循环而不是数组的长度,这只是一种挑剔。这是代码

int count = 0;
int max = 0;
char index = '1';
int consecutiveOnePairs = 0;
int numberOfOnes = 0;

Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
String b = Integer.toBinaryString(n);
char[] arr = b.toCharArray();
System.out.println(arr);

for (int i = 0; i < arr.length; i++) {
    if (arr[i] == index)
    {
        count++;
        numberOfOnes++;
    }

    if((i + 1 == arr.length && count > 1) || arr[i] != index)
    {
        if(count > 1)
            consecutiveOnePairs++;
        if (count > max)
            max = count;
        count = 0;
    }
}

System.out.println("Total Number of 1's in " + n + " is " + numberOfOnes);
System.out.println("Total Number of Consecutive 1's in " + n + " is " + consecutiveOnePairs);
System.out.println("Greatest Number of Consecutive 1's in " + n + " is " + max);
scan.close();

<强>输出

13247
11001110111111
Total Number of 1's in 13247 is 11
Total Number of Consecutive 1's in 13247 is 3
Greatest Number of Consecutive 1's in 13247 is 6

511
111111111
Total Number of 1's in 511 is 9
Total Number of Consecutive 1's in 511 is 1
Greatest Number of Consecutive 1's in 511 is 9

887
1101110111
Total Number of 1's in 887 is 8
Total Number of Consecutive 1's in 887 is 3
Greatest Number of Consecutive 1's in 887 is 3

答案 4 :(得分:0)

如果您使用Java 8,则可以尝试以下代码段:

 public int maxOneConsecutive(int x)
  {
    String intAsBinaryStr = Integer.toBinaryString(x);
    String[] split = intAsBinaryStr.split("0");
    return Arrays.stream(split)
        .filter(str -> !str.isEmpty())
        .map(String::length)
        .max(Comparator.comparingInt(a -> a)).orElse(0);
  }