class Solution { public: int myAtoi(string str) { if(str.empty()) { return 0; }
string::const_iterator itor = str.begin(); for(; itor != str.end(); ++itor) { if(isspace(*itor)) { continue; } break; } long long nRet = 0; // 如果这里定义的数据类型为int,后面的实现方式会产生溢出错误 bool isPas = true; if(*itor == '+') { ++itor; } else if(*itor == '-') { ++itor; isPas = false; } for(; itor != str.end(); ++itor) { if(*itor >= '0' && *itor <= '9') { // long long llTemp = nRet * 10; // 如果nRet是int类型,则nRet * 10就已经溢出了, // 将其赋值给long long型的数据也是错误的结果。 // 所以nRet必须为long long型数据。 // llTemp = llTemp + *itor - '0'; nRet *= 10; nRet += *itor - '0'; bool isOver = isPas ? nRet > INT_MAX : -nRet < INT_MIN; if(isOver) { return isPas ? INT_MAX : INT_MIN; } } else { return isPas ? nRet : -nRet; } } return isPas ? nRet : -nRet; }
};
atoi — 隐式数据类型转换
最新推荐文章于 2024-04-19 01:00:00 发布