I am reading in a string of ints (1112, 1234, 1892, 1987) and for the digits that are greater than its left and right neighbors, I will replace that digit with an 'X' (i.e. 1892 -> 18X2, 1987 -> 1X87). Note that the digits in the first and last spot will never be replaced, because they only have one neighbor to compare to.
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <sstream>
usingnamespace std;
int main() {
int in;
cin >> in; //read in the first integer that specifies how many strings there will be
vector<int> v; //create a vector to store the ints
int integer;
for (int i = 0; i < in; i++) {
cin >> integer;
v.push_back(integer); //vector v should now have all the strings
}
stringstream os;
string st;
//loop through the number of strings
for (int j = 0; j < in; j++) {
os << v.at(j); //converting int to a string so we can iterate through it
st = os.str(); //store the newly converted string into a string variable
//loop through each individual digit of each 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;
os.str(string()); //clears the string in the vector so we can take the next input
os.clear();
}
return 0;
}
Input: 1, 121212121212
Expected output: 1X1x1x1x1x12
Actual output: 214X4X3X47
I realize that number 2147483647 is the maximum value for an int. Why is that showing up though?
Do not give dangerous advice which cannot really be applied in this situation.
Replacing integer with floating point numbers will do nothing, but made situation worse:
1 2 3 4 5 6 7 8 9 10
#include <iostream>
#include <iomanip>
int main()
{
int i = 1234567890;
float f = 1234567890;
std::cout << i << '\n';
std::cout << std::fixed << f;
}
1234567890
1234567936.000000
Floating point numbers are imprecise by design.
Replacing float with double will just increase number of digits which would be correct to about 15. This will not fix anything.
@pattrick128: use longlong or unsignedlonglong instead of int. If you will need even larger numbers, you will have to either maniulate exclusively strings or use some big integers library
@MiiNiPaa: I actually need to store whatever the test cases indicates. One of the test cases had over 30 digits in one string, so I don't think longlong will cut it. What if I used a vector<string> instead?