Cavity map

This is a coding question on Hackerrank.

We're given a bunch of strings of ints, say 1112, 1234, and 1842. If a certain digit in the string is bigger than both its neighbors, we will replace that digit with an 'X'. (In this case, 1842 -> 1X42) Clearly, the first and last digit will have nothing happen to them since they don't have a second neighbor to compare to.

I stored these strings of ints into a vector, and I have a check for the first and last digit in the string. If we're working with the string of ints "1842", I have two checks: 1. last digit will have no neighbor after it, so I'm checking for the value at k+1 -> if it's null, then do nothing to the digit. 2. same thing with first digit, if there's nothing before it at k-1, do nothing.

1
2
3
4
5
6
7
8

//loop through each individual digit of each string (in this case, 4 digits per string)
        for (int k = 0; k < st.length(); k++) {
            //if the variable is at edge, move on to the next int
            if (v.at(k+1) == null || v.at(k-1) == null) {
                break;
            }



The compiler is complaining that "null" is not declared. I do have #include <cstddef> in the header. Is there any other way I can go about this?
You could just iterate from index 1 to size - 1
I ran into another problem, actually.

1
2
3
4
5
6
7
8
9
10
        //loop through each individual digit of each string (in this case, 4 digits per string)
        //starting from 1 to length-1 to avoid the edges, which we don't care about
        for (int k = 1; k < st.length()-1; k++) {
            //if current is greater than both neighbors, change that to 'X'
            if (st.at(k) > st.at(k+1) && st.at(k) > st.at(k-1)) {
                st.at(k) = 'X'; //replace that digit with an 'X'
            }
        }
        
        cout << st << endl;


When I'm testing this against 12121212121, the returned output is "214X4X3X47", when it should be "12X2X2X2X21". I'm assuming that output is the maximum integer value "2147483647". Why's that?
Last edited on
Topic archived. No new replies allowed.