标签:style blog class c code java
http://zhedahht.blog.163.com/blog/static/25411174200731139971/
代码如下:
bool bValid = true; int str2int_core(const char *digit,bool minus) { long long sum = 0; int flag = minus ? -1:1; while(*digit!=‘\0‘) { if (*digit>=‘0‘&&*digit<=‘9‘) { sum = 10*sum + flag*(*digit-‘0‘); // whether overflow ? if ((!minus && sum > (signed int)0x7fffffff) || (minus && sum < (signed int)0x80000000)) { sum = 0; break; } digit ++; } else { sum = 0; break; } } if (*digit==‘\0‘) { bValid = true; } return (int)sum; } int str2int(const char *str) { bValid = false; long long sum = 0; if (NULL==str || *str==‘\0‘) return (int)sum; bool minus = false; if (*str==‘+‘) { str++; } else if (*str==‘-‘) { str++; minus = true; } if (*str==‘\0‘) return (int)sum; return str2int_core(str,minus); } void test_case(const char *str) { int sum = str2int(str); if (bValid) cout<<sum<<endl; else cout<<"Invalid input!"<<endl; }
17.把字符串转换成整数atoi,布布扣,bubuko.com
标签:style blog class c code java
原文地址:http://www.cnblogs.com/hellogiser/p/3738741.html