Skip to content

Instantly share code, notes, and snippets.

@guolinaileen
Last active December 11, 2015 17:09
Show Gist options
  • Save guolinaileen/4632929 to your computer and use it in GitHub Desktop.
Save guolinaileen/4632929 to your computer and use it in GitHub Desktop.
careful about the divisor
class Solution {
public:
string convert(string s, int nRows) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if(nRows<=1) return s;
int length=s.length();
int numberItems=2*(nRows-1);
int zones=length/numberItems+(length%numberItems==0? 0: 1);
string result="";
for(int row=0; row<nRows; row++)
{
for(int z=0; z<zones; z++)
{
if(z*numberItems+row<length)
{
result+=s[z*numberItems+row];
}
if(row!=0 && row!=nRows-1 && (z+1)*numberItems-row<length)
{
result+=s[(z+1)*numberItems-row];
}
}
}
return result;
}
};
public class Solution {
public String convert(String s, int nRows) {
// Start typing your Java solution below
// DO NOT write main() function
int length=s.length();
if(length<nRows || nRows==1) return s;
int numbers=2*(nRows-1);
int sections=(length%numbers==0? length/numbers: length/numbers+1);
StringBuffer sb=new StringBuffer();
for(int i=0; i<nRows; i++)
{
for(int j=0; j<sections; j++)
{
if(i+numbers*j<length) sb.append(s.charAt(i+numbers*j));
if(i>0 && i<nRows-1 && numbers*(j+1)-i<length ) sb.append(s.charAt(numbers*(j+1)-i));
}
}
return sb.toString();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment