# A simple c++ solution with detailed explanation

• i think this is a math problem, not a coding problem.

we can get the formula of this problem as follows

if row==1 or row == numRows

• y = f(row, col) = row + (col-1)(2numRows-2)-1

else there are two values for each col, where

• y1 = f(row, col) = row + (col-1)(2numRows-2)-1
• y2 = f(row, col) = row + col*(2*numRows-2) - 1 -(i-1)*2

where: y is the index of the string for a specified row and colume

so the solution is:

``````class Solution {
public:
string convert(string s, int numRows) {
if (numRows==1)
{
return s;
}
size_t len = s.length();
string strBuf;
for (int i = 1; i <= numRows; i++)
{
for (int j = 1; j <= len; j++)
{
if (i==1 || i==numRows)
{
int pos = i + (j - 1)*(2 * numRows - 2) - 1;
if (pos>=len)
{
break;
}
strBuf += s[pos];
}
else
{
int pos = i + (j - 1)*(2 * numRows - 2) - 1;
if (pos >= len)
{
break;
}
strBuf += s[pos];
pos = i + j*(2 * numRows - 2) - 1 - (i - 1) * 2;
if (pos >= len)
{
break;
}
strBuf += s[pos];
}
}
}
return strBuf;
}
};``````

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