程序员面试题100题第17题——字符串转化为整数
题目:把输入的字符串转化为整数,如:“-456” 输出456、“+456”输出456,“456”输出“456”,如果是非法输入,则输出0,并提示错误。
代码:
long long strToNum( const char* pStr) { long long num=0; int flag=1; if(pStr==NULL) { cout << "is null!\n"; return 0; } if(*pStr=='-') { flag=-1; pStr++; }else if(*pStr=='+') { pStr++; }else{ } while(*pStr != '\0') { if((*pStr)>='0' && (*pStr)<='9') { num =num*10 + (*pStr-'0'); if(num > std::numeric_limits<long long>::max()) { num=0; cout << "over flow!\n"; return num; } }else{ num=0; cout << "not a number!\n"; return num; } pStr++;//while中总是忘记 } num *=flag; return num; }