前言前幾天博主在新浪微薄上看到耗子叔叔考察了atoi的編寫,周四博主也要面試阿里(ps:雖然博主LNMP方向,但是還是有信心拼一把),這裡也自己實現一下這兩個函數,防止面試問到答不出來
atoi
#include <stdio.h>#include <stdlib.h>#define INT_MAX 2147483647#define INT_MIN -2147483648int myatoi(const char *s){int val, flag;unsigned int cutlim, cutoff;// 判斷是否為空白if (s == NULL)return 0;// 去除空格和定位字元while (*s == ' ' || *s == '\t')s ++;// 判斷符號if (*s == '-') {flag = 1;s ++;} else {flag = 0;if (*s == '+')s ++;}// 注意越界cutoff = flag ? (unsigned int) INT_MAX + 1 : INT_MAX;cutlim = cutoff % 10;cutoff /= 10;for (val = 0; *s >= '0' && *s <= '9'; s ++) {if (val > cutoff || (val == cutoff && *s - '0' > cutlim)) {return flag ? INT_MIN : INT_MAX;}val = 10 * val + *s - '0';}if (flag)return val * -1;elsereturn val;}int main(void){char str[100];int num;while (scanf("%s", str) != EOF) {num = myatoi(str);printf("%d\n", num);}return 0;}
itoa
#include <stdio.h>#include <stdlib.h>#define N 15/** * 異或交換兩個數 */void swap(char *a, char *b){if (*a != *b) {*a = *a ^ *b;*b = *a ^ *b;*a = *a ^ *b;}}/** * 編程實現windows平台整型轉字串代碼 */void itoa(int value, char *str){int i, j, k;// 處理負數if (value < 0) {str[0] = '-';value *= -1;} else {str[0] = '+';}for (i = 1; value; i ++, value /= 10) {str[i] = value % 10 + '0';}// 字串逆序for (j = 1, k = i - 1; j <= k; j ++, k --) {swap(str + j, str + k);}// 補字串結束標識str[i] = '\0';// 正數前移一位if (str[0] != '-') {for (j = 1; j <= i; j ++) {str[j - 1] = str[j];}}}int main(void){int value;char str[N];while (scanf("%d", &value) != EOF) {itoa(value, str);printf("%s\n", str);}return 0;}