# Simple c++ solution beats 99.3% of the solutions

• ``````class Solution {
public:
string convert(string s, int numRows) {
int size = s.size();
string sNew = "";
int newArrayIndex = 0;
int oldArrayIndex = 0;

//Handle the 1 row case
if(numRows == 1) {
sNew+=s;
return sNew;
}

for(int i=0; i<numRows; i++) {
oldArrayIndex = i;
int skipElements1, skipElements2;
//For the first and last rows the number of elements to be skipped is the same.
if(i == 0 || i == (numRows-1)) {
skipElements1 = ((numRows-1)-(i%(numRows-1))) * 2;
skipElements2 = skipElements1;
} else {
//For the middle rows, the number of elements to be skipped depends on the direction of movement.
skipElements1 = ((numRows-1)-(i%(numRows-1))) * 2;
skipElements2 = (i%(numRows-1))*2;
}
while(oldArrayIndex < size) {
sNew+= s[oldArrayIndex];
newArrayIndex++;
oldArrayIndex = oldArrayIndex + skipElements1;
swap(skipElements1, skipElements2);
}
}
return sNew;
}
};
``````

The zigzag pattern actually is a re-arrangement of strings by skipping certain elements to get the next element in the new string. The number of elements to be skipped depends on the row which you are operating on and the whether you are moving up or down in the zigzag.

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.