【演算法】【將字串轉換成int】
阿新 • • 發佈:2019-02-15
之前還使用過遞迴來計算,不過現在已經記不起來了
#include <stdio.h> #include <error.h> #include <math.h> #define ERROR -22 #define DEBUG 0 static int CheckValid(char *str) { // debug #if DEBUG printf("%s\n", str); #endif // 魯棒性為第一位考慮 if(str==NULL) goto err; char *ptr = str; if(!(*ptr=='-'||((*ptr-'0')>=0&&(*ptr-'0'<=9)))){ goto out; } ptr++; while(*ptr){ if(!((*ptr-'0')>=0&&(*ptr-'0'<=9))){ goto out; } ptr++; } return 0; out: fprintf(stderr, "%s is invalid\n", str); err: return ERROR; } static long int CharTolong(char *str) { // debug #if DEBUG printf("%s\n", str); #endif long int ret = 0; int flag = 0; int max = pow(2,(sizeof(int)*8)-1)-1; int min = pow(2,(sizeof(int)*8)-1)*-1; #if DEBUG printf("max is %d\n", max); printf("min is %d\n", min); #endif char *ptr = str; if(*ptr=='-'){ flag = 1; ptr++; } while(*ptr){ ret = ret*10+(*ptr-'0'); if(flag==1&&ret>(max+1)) return ERROR; if(flag==0&&ret>max) return ERROR; ptr++; } if(flag==1) ret *=-1; return ret; } int main() { char str1[] = "2345"; if(!CheckValid(str1)){ int ret_str1 = CharTolong(str1); if(ret_str1!=ERROR||ret_str1==ERROR&&strcmp(str1,"-22")==0) printf("%ld\n", CharTolong(str1)); } char str2[] = "-456"; if(!CheckValid(str2)){ int ret_str2 = CharTolong(str1); if(ret_str2!=ERROR||ret_str2==ERROR&&strcmp(str2,"-22")==0) printf("%ld\n", CharTolong(str2)); } char str3[] = "0678"; if(!CheckValid(str3)){ int ret_str3 = CharTolong(str3); if(ret_str3!=ERROR||ret_str3==ERROR&&strcmp(str3,"-22")==0) printf("%ld\n", CharTolong(str3)); } char str4[] = "gy789"; if(!CheckValid(str4)){ int ret_str4 = CharTolong(str4); if(ret_str4!=ERROR||ret_str4==ERROR&&strcmp(str4,"-22")==0) printf("%ld\n", CharTolong(str4)); } char str5[] = "890-8"; if(!CheckValid(str5)){ int ret_str5 = CharTolong(str5); if(ret_str5!=ERROR||ret_str5==ERROR&&strcmp(str5,"-22")==0) printf("%ld\n", CharTolong(str5)); } }