有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何计算数组中的连续数字组

我有一个简单的问题

例如,有一个像int[] myArr = {1,2,3,4,9,12,17,23,34,54,55,56}这样的数组,我想数一数像1,2,3,4这样的连续数字组有多少个,第一个是54,第55,第56个是其他,总共2个相关数字组


共 (1) 个答案

  1. # 1 楼答案

    将来,试着包含更多关于你尝试过什么或你研究过什么的信息。正如Azro所说,我们是来帮助你的,而不是为你完成任务

    int[] myArr = {1,2,3,4,9,12,17,23,34,54,55,56};
    int consecutiveSums = 0;
    
    // Iterate through the array
    for (int i = 0; i < myArr.length; i++) {
        // Check if the next value is consecutive
        if (i + 1 < myArr.length && myArr[i] + 1 == myArr[i+1]) {
            consecutiveSums ++;
            // Skip any remaining consecutives until we reach a new set
            while (i + 1 < myArr.length && myArr[i] + 1 == myArr[i+1]) {
                i++;
            }
        }
    }
    
    System.out.println(consecutiveSums);