简体   繁体   中英

How am i missing last element of an array

I am facing a problem with

#include<iostream>
using namespace std;
bool check(int input)
{
    int count = 0;
    int temp;
    int val[] = { 2,0,2,1 };
    temp = input;
    while (temp != 0) {
        count++;
        temp /= 10;
    }
    int *arr = new int[count];
    for (int i = count; i >= 0; i--)
    {
        arr[i] = input % 10;
        input /= 10;
    }
    temp = 0;
    int res = count;
    for (int j = 0; j < 5; j++)
    {
        for (int k = 0; k < res; k++)
        {
            if (val[j] == arr[k])
            {
                cout << "CHECKING : " << arr[k] << endl;;
                j = j + 1;
                for (int l = k; l < (count - 1); l++)
                {
                    arr[l] = arr[l + 1];
                }
                res=res-1;
                temp++;
                k = 0;
                if (temp == 4)
                {
                    return true;
                }
            }
        }
    }
    cout << temp;
    return false;
}
int main()
{
    int input;
    cin >> input;
    if (check(input) == true)
    {
        cout <<endl << "YES!!" << endl;
    }
    else
    {
        cout <<endl <<"NO!!" << endl;
    }
}

this program I have to check if input number have 2021 number or not if input is 2002021 output should be yes or input is 2002024 output should be no because 1(2021) is missing now the thing is my program works fine logically but i dont know how my array last element is missing like if i put 200022021 = then the output will be no but if I am giving 200022012 it is saying yes i dont know how my last element of array is missing.

You got the loop counter wrong:

for (int i = count; i >= 0; i--)
{
    arr[i] = input % 10;
    input /= 10;
}

In the first iteration i == count and arr[count] is out-of-bounds. Last iteration i == 1 (because when (i >= 0) == false you stop the loop) and you never assign to arr[0] .

You can call such mistakes history when you use either std::vector or std::array (for dynamic / fixed size, resp.) and use their reverse iterators ( rbegin and rend ) to iterate all elements in reverse.

Just because I can't be bothered looking for the bug:

You can use the same method as you do for separating the single digits to examine the number in groups of four digits.

x % 10 is the last digit; x % 100 is the last two digits; x % 1000 is the last three digits, and so on.
Add a division by 10 to "shift" the number:

bool check(int input)
{
    while (input > 2020)
    {
        if (input % 10000 == 2021)
        {
            return true;
        }
        input /= 10;
    }
    return false;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM