Leetcode 8. String to Integer (atoi) atoi函数实现 (字符串)

Leetcode 8. String to Integer (atoi) atoi函数实现 (字符串)

题目描述

实现atoi函数,将一个字符串转化为数字

测试样例

Input: "42"
Output: 42 Input: " -42"
Output: -42 Input: "4193 with words"
Output: 4193 Input: "words and 987"
Output: 0

详细分析

这道题的corner cases非常多,请务必确保下面cases都能通过的情况下再提交。

"42"
"words and 987"
"-91283472332"
"0-1"
"-000000000000001"
" 0000000000012345678"
"10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000522545459"
"-2147483647"
"-2147483648"
"2147483648"
"2147483649"
""
"7"
" +0 123"

算法实现

class Solution {
public:
string trim(const std::string&str){
string nstr;
int i=0;
while(isspace(str[i])){
i++;
} for(;i<str.length();i++){
if(isspace(str[i])){
break;
}
nstr +=str[i];
}
return nstr;
} int myAtoi(string str) {
str = trim(str);
if(str.length()==0 || (str[0]!='+'&&str[0]!='-'&& !isdigit(str[0]))){
return 0;
} int i=0; //consume sign char
if(str[0] =='+' || str[0]=='-'){
i++;
}
string nstr;
while(isdigit(str[i])){
nstr+=str[i];
i++;
}
if(nstr.length()==0){
return 0;
}
i=0;
// consume meaningless zeros
while(nstr[i]=='0'){
i++;
}
nstr = nstr.substr(i);
long long result = 0L;
unsigned long long exp = 1;
for(int k=nstr.length()-1;k>=0;k--){
result += ((int)(nstr[k]-'0'))*exp; if(exp> numeric_limits<int>::max()){
return str[0]=='-'?numeric_limits<int>::min():numeric_limits<int>::max();
}
exp*=10;
if(result> numeric_limits<int>::max()){
return str[0]=='-'?numeric_limits<int>::min():numeric_limits<int>::max();
}
}
return str[0]=='-'?-result:result;
}
};
上一篇:11.IntelliJ IDEA详细配置和使用教程(适用于Java开发人员)


下一篇:打造Linux三流娱乐环境,二流办公环境,一流Java开发环境