Created
April 16, 2012 12:14
-
-
Save bxshi/2398331 to your computer and use it in GitHub Desktop.
CareerCup 150 1.2 @1point3acres
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* CareerCup 150 4/16-4/22 1.2 | |
* | |
* slaink@1point3acres | |
* | |
*/ | |
/* | |
* 反转字符串的话最容易的就是从两端(用i,j)开始swap,最后到i,j重合或者i>j. | |
* 这样会有一个问题就是strlen是怎么算出来的?如果是遍历寻找\0的话,那么这就有了一个n了. | |
* 再加上上面反转字符串的1/2n,最后复杂度还是一次的. | |
* 但是总觉得题目不能这么简单吧! | |
* | |
* 想不出来什么别的方法了,添加一个cheat way吧,完全就是倒序输出…… | |
*/ | |
#include <stdlib.h> | |
#include <stdio.h> | |
#include <string.h> | |
char *dumb_way(char *string); | |
void cheat_way(char *string); | |
int main(int argc, char **argv) | |
{ | |
char *reversed; | |
if(argc != 3){ | |
printf("usage: <program name> <type 1:dumb-way 2:cheat-way> <string>\n"); | |
return 0; | |
} | |
switch(atoi(argv[1])) { | |
case 1: | |
reversed = dumb_way(argv[2]); | |
printf("%s\n", reversed); | |
break; | |
case 2: | |
cheat_way(argv[2]); | |
break; | |
} | |
return 0; | |
} | |
char *dumb_way(char *string) | |
{ | |
size_t i,j; | |
size_t len = strlen(string); | |
char tmp; | |
i=0; | |
j = len - 1; | |
while(i<j) { | |
tmp = string[i]; | |
string[i++] = string[j]; | |
string[j--] = tmp; | |
} | |
return string; | |
} | |
void cheat_way(char *string) | |
{ | |
size_t i = strlen(string)-1; | |
while(i){ | |
printf("%c",string[i--]); | |
} | |
printf("\n"); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment