Skip to content

Instantly share code, notes, and snippets.

@guolinaileen
Last active December 14, 2015 13:38
Show Gist options
  • Save guolinaileen/5094949 to your computer and use it in GitHub Desktop.
Save guolinaileen/5094949 to your computer and use it in GitHub Desktop.
class Solution {
public:
int atoi(const char *str) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if(*str=='\0') return 0;
while(*str==' ') str++;
bool negative=false;
if(*str=='-')
{
negative=true; str++;
}else if(*str=='+')
{
str++;
}
int result=0;
while(*str<='9' && *str>='0')
{
if((INT_MAX-(*str-'0'))/10<result)
{
return negative? INT_MIN:INT_MAX;
}
result=10*result+*str-'0';
str++;
}
return negative? -result:result;
}
};
public class Solution {
public int atoi(String str) {
// Start typing your Java solution below
// DO NOT write main() function
int length=str.length();
if(length==0) return 0;
int index=0; boolean negative=false; int result=0;
while(str.charAt(index)==' ')
{
index++;
}
if(str.charAt(index)=='-')
{
negative=true; index++;
}else if(str.charAt(index)=='+')
{
negative=false; index++;
}
for(; index<length; index++)
{
if(str.charAt(index)>='0' && str.charAt(index)<='9')
{
if(result<=(Integer.MAX_VALUE-(str.charAt(index)-'0'))/10)
{
result=result*10+str.charAt(index)-'0';
}else return negative? Integer.MIN_VALUE: Integer.MAX_VALUE;
}
else break;
}
return negative? -result: result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment