简单笔试题2

1. 判断回文字符串

#include 
#include 
#include 

int my_getline(char * line, int max_size){
	int c;
	int length = 0;
	while ((c = getchar()) != EOF && length < max_size) {
		line[length++] = c;
		if('\n' == c || length == max_size - 2)
			break;
	}
	line[length] = '\0';
	return length;
}

int main(){
 
 size_t length = 1024;
 char *line = (char *)malloc(sizeof(char) * length);
 ssize_t read;
 bool isPalindrome = true;
 printf("Please input string: ");
 while((read = getline(&line,&length,stdin)) != -1){
  //while((read = my_getline(line,length)) != 0){
  printf("Retrieved line of length %ld, %u :\n", read, length);
  int count = strlen(line);
  count = count - 1;
  printf("count is %d, The string is: %s",count,line);
 
     for(int i=0,j = count -1;i <= count/2 && i<=j,j>= count/2;i++,j--)
     {
    	 printf("line: %c, %c\n",line[i],line[j]);
         if(line[i] == line[j]) continue;
	 else {
             isPalindrome = false;
	     break;
	 } 
     }
     if(isPalindrome != true) printf("is not palindrome\n");
     else printf("is palindrome\n");
     isPalindrome = true;
 }
}

2. 循环右移

#include 
#include 
//#include 
#include 

#define MAX_SIZE 100
void rotateRight(char *a,int m, int length){
	char tmp1,tmp2;
	tmp1 = tmp2 = a[0];
	int k = 0;
	int n = 0;//for loop;
	printf("m is %d length is %d\n",m,length);
	for(int i=0,j = 0; i <= length - 1 ; i++){
		if((j+m) > length - 1){
			k = (j+m)%length;

		} else {
			k = j + m;
		}
		printf("k is %d\n",k);
		tmp2 = tmp1;
		tmp1 = a[k];
		a[k] = tmp2;
		j = k;
		if(k == n){
		   printf("n is %d\n",n);
		   j = j + 1;
		   n = j;
		   tmp2 = tmp1 = a[j];
		   continue;
		}

	}
	//std::cout << "rotate result is " << a <> N;
	printf("Input N:%d\n",N);
	read = getline(&line,&length,stdin);//读取回车符
	printf("Input string: \n");
	if((read = getline(&line,&length,stdin)) != -1){
		printf("Input string read: %zd\n",read);
		printf("Input string is: %s\n",line);
		int strlength = strlen(line);
		printf("strlength: %d\n",strlength);
		int m = N%(strlength-1);//减去回车符
		printf("m is: %d\n",m);
		//for(int i = 0;i < m; i++){
		rotateRight(line,m,strlength-1);
		//}
	}
	}
	/*int n;
	char s[MAX_SIZE];
	printf("Input rotate number: \n");
	while(scanf("%d",&n) == 1) {
		printf("rotate number is %d\n",n);
		printf("input string : \n");
		scanf("%s",s);
		printf("\n");
		printf("input string is %s\n",s);
		loopMove(s,n);
		printf("after rotate is %s\n",s);
	}*/
	
	
}

 

你可能感兴趣的:(Algorithm)