leetcode 第6-8题

     ZigZag Conversion 该题是个找规律题,每行的字符位置距离呈现周期性(d=2*nRnows-2)变化然后处理好每个周期内的情况即可。代码如下

class Solution {
public:
    string convert(string s, int nRows) {
        if(nRows==1)return s;
        int k,len=s.size();
        string result="";
        int d=2*nRows-2;
        for(int j=0;j                 result+=s[j]; 
        for(int i=1;i             k=d-2*(i);
            for(int j=i;j                 result+=s[j]; 
                if(j+k                   result+=s[j+k];
           
            }
        }
        for(int j=nRows-1;j                 result+=s[j];
        return result;
    }
};

Reverse Integer 与String to Integer (atoi) 都可以看成是对字符数组与整数之间相互转化,其中atoi 函数,开始写的时候,总是容易或略比如空格这些特殊字符需要处理的情况代码依次如下:

class Solution {
public:
    int reverse(int x) {
        int flag=1;
        string s="";
        if(x<0){x=-x;flag=-1;}
        int i=0;
        while(x)
        {
            s+=('0'+(x%10));
            x=x/10;
            i++;           
        }
        for(int i=0;i                 x=x*10+s[i]-'0';}
        return flag*x;
       
    }
};

class Solution {//atoi
public:
     int atoi(const char *str) {
        long long result=0;int flag=1;int tmp=0;
        for(int i=0;i         {      if(tmp==0){
                   if(str[i]=='+'||str[i]=='-'||('0'<=str[i]&&str[i]<='9'))tmp=1;
                   if(str[i]==' '||str[i]=='\n'||str[i]=='\t')continue;
                   if(i                        if((str[i]=='+')&&'0'<=str[i+1]&&str[i+1]<='9')continue;
                       if(str[i]=='-'&&'0'<=str[i+1]&&str[i+1]<='9'){flag=-1;continue;}
           
                   }
               }
               if(str[i]=='+'||str[i]=='-'||('0'<=str[i]&&str[i]<='9'))tmp=1;
               if('0'<=str[i]&&str[i]<='9')result=result*10+str[i]-'0';
                else break;
        }
        if(result>2147483647&&flag>0) return 2147483647*flag;
        if(result>2147483647&&flag<0)return 2147483648*flag;
        return flag*result;
    }
};

你可能感兴趣的:(算法,面试)