# A Mathematical Solution

• ``````public class Solution {
public String convert(String s, int numRows) {
int sLength = s.length();
char[][] normalRows = new char[numRows][sLength];

// initialise
for(int i = 0; i < numRows; i++){
for(int j = 0; j < sLength; j++){
normalRows[i][j] = '\$';
}
}

if(numRows == 1)
return s;

if(numRows == 2){
for(int i = 0; i < sLength; i++){
normalRows[i%2][i/2] = s.charAt(i);
}

String result = "";
for(int i = 0; i < 2; i++){
for(int j = 0; j < sLength; j++){
if(normalRows[i][j] != '\$')
result += normalRows[i][j];
}
}
return result;
}

if(numRows == 3){
for(int i = 0; i < sLength; i++){
normalRows[i % 4 == 3 ? 1 : i % 4][(i / 4) * 2 + (i % 4 == 3 ? 1 : 0)] = s.charAt(i);
}

String result = "";
for(int i = 0; i < numRows; i++){
for(int j = 0; j < sLength; j++){
if(normalRows[i][j] != '\$')
result += normalRows[i][j];
}
}
return result;
}

int numEachGroup = numRows + numRows - 2;
for(int i = 0; i < sLength; i++){
int columnNumber = (i/numEachGroup) * 2 + ((i % numEachGroup) >= numRows ? 1 : 0);
int rowNumber = columnNumber % 2 == 0 ? (i % numEachGroup % numRows):(numRows - 2 - (i % numEachGroup % numRows));
normalRows[rowNumber][columnNumber] = s.charAt(i);
}

String result = "";
for(int i = 0; i < numRows; i++){
for(int j = 0; j < sLength; j++){
if(normalRows[i][j] != '\$'){
result += normalRows[i][j];
}
}
}
return result;
}
``````

}

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