Skip to content

Instantly share code, notes, and snippets.

@luoxiaoxun
Created July 9, 2013 07:20
Show Gist options
  • Save luoxiaoxun/5955338 to your computer and use it in GitHub Desktop.
Save luoxiaoxun/5955338 to your computer and use it in GitHub Desktop.
Implement atoi to convert a string to an integer. Hint: Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases. Notes: It is intended for this problem to be specified vaguely (ie, no given input specs). You are responsible to gather all the input requiremen…
C++:
class Solution {
public:
int atoi(const char *str) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
bool negative=false;
while(*str==' ') str++;
if(*str=='-'){
negative=true;
str++;
}
if(*str=='+') str++;
long long res=0;
while(*str!='\0'){
if(*str>='0'&&*str<='9')
res =res*10+*str-'0';
else break;
str++;
}
res =negative?-res:res;
if(res>INT_MAX) return INT_MAX;
if(res<INT_MIN) return INT_MIN;
return res;
}
};
Java:
public class Solution {
public int atoi(String str) {
// Start typing your Java solution below
// DO NOT write main() function
if(str==null||str.length()==0) return 0;
char[] ch=str.toCharArray();
boolean negative=false;
int index=0;
while(ch[index]==' ') index++;
if(ch[index]=='-'){
negative=true;
index++;
}
if(ch[index]=='+') index++;
long res=0;
while(index<ch.length){
if(ch[index]>='0'&&ch[index]<='9'){
res =res*10+ch[index]-'0';
index++;
}else break;
}
res=negative?-res:res;
if(res>Integer.MAX_VALUE) return Integer.MAX_VALUE;
if(res<Integer.MIN_VALUE) return Integer.MIN_VALUE;
return (int)res;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment