此程序还没有判读sum是否溢出,待续。。
// 程序员面试100题(算法)之把字符串转换成整数#include "stdafx.h"#include <iostream>using namespace std;int state = 0;int ConvertStr(char *str){ int num = 0; long sum = 0; if(NULL == str) { cout << "input is empty" << endl; state = 1; } else { char symbol = *str; if(symbol == '+' || symbol == '-') { str++; } while(*str != '\0') { if(*str >= '0' && *str <= '9') { num = *str - '0'; sum = sum * 10 + num; str++; } else { state = 1; break; } } if(symbol == '-') { sum = 0 - sum; } } return sum;}int _tmain(int argc, _TCHAR* argv[]){ char *str = "-5462458"; long number = ConvertStr(str); if(1 == state) cout << "Wrong input" <<endl; else cout << number << endl; return 0;}
联系客服