将字符串反转,即“abcde”->"edcba"
C语言实现:
【转自http://www.kanzhun.com/mianshiti/456.html?sid=mail_18200_2_detail&ka=mail-18200-2-detail3】
#include <stdio.h> #include <stdlib.h> #include <string.h> int reverse(int i) { int flag; if(i > 0) { flag = 1; } else { flag = -1; } i *= flag; char *tmp = (char*)malloc(sizeof(char)*100); sprintf(tmp, "%d", i); printf("%s", tmp); int len = strlen(tmp); int j; char a; for(j = 0; j < len/2; ++j) { a = tmp[j]; tmp[j] = tmp[len-j-1]; tmp[len-j-1] = a; } i = atoi(tmp); i *= flag; free(tmp); return i; }
int main(void) { int i; scanf("%d", &i); i = reverse(i); printf(" %d", i); return 0; }
Python实现
方法一:先把字符串转换成列表,利用列表的reverse方法反转列表,再用字符串的join方法连接列表
方法二:利用字符串的倒序切片 a[::-1]