atoi和itoa的編程實現

來源:互聯網
上載者:User

前言前幾天博主在新浪微薄上看到耗子叔叔考察了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;}


相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.