008 String to Integer (atoi) 字符串转换为整数

时间:2024-04-05 23:04:35

详见:https://leetcode.com/problems/string-to-integer-atoi/description/

实现语言:Java

class Solution {
public int myAtoi(String str) {
int index =0;
Long total = new Long(0);
int sign = 1;
while(index < str.length() && str.charAt(index) == ' '){
++index;
} if(index == str.length()){
return (int)(total*sign);
} if(str.charAt(index) == '-' || str.charAt(index) == '+'){
sign = str.charAt(index) == '-'?-1 : 1;
index++;
} while(index < str.length() && str.charAt(index) >= '0' && str.charAt(index) <= '9'){
total = total *10 + str.charAt(index) - '0';
++index; if(total > Integer.MAX_VALUE){
return sign==1?Integer.MAX_VALUE:Integer.MIN_VALUE;
}
}
return (int)(total*sign);
}
}

实现语言:C++

class Solution {
public:
int myAtoi(string str) {
int n=str.size();
if(n==0||str.empty())
{
return 0;
}
int sign=1,base=0,i=0;
while(i<n&&str[i]==' ')
{
++i;
}
if(str[i]=='+'||str[i]=='-')
{
sign=str[i++]=='+'?1:-1;
}
while(i<n&&str[i]>='0'&&str[i]<='9')
{
if(base>INT_MAX/10||(base==INT_MAX/10&&str[i]-'0'>7))
return sign==1?INT_MAX:INT_MIN;
base=base*10+str[i++]-'0';
}
return sign*base;
}
};

参考:http://www.cnblogs.com/grandyang/p/4125537.html