Skip to content

Instantly share code, notes, and snippets.

@engtomhat
Created August 2, 2017 03:02
Show Gist options
  • Save engtomhat/2cfa425e526edff7a660c6948945d4f6 to your computer and use it in GitHub Desktop.
Save engtomhat/2cfa425e526edff7a660c6948945d4f6 to your computer and use it in GitHub Desktop.
String to Integer (atoi)
public class StringToInteger {
public int myAtoi(String str) {
int result = 0;
int multiplier = 1;
int startIndex = -1;
int endIndex = -1;
int index = 0;
boolean scanNumber = false;
boolean signAllowed = true;
boolean spaceAllowed = true;
while (index < str.length()) {
char letter = str.charAt(index);
if(scanNumber) {
// Mark the end of number
if(isNumber(letter)) {
endIndex = index;
index++;
} else {
break;
}
} else {
// Read spaces
if(isSpace(letter)) {
if(spaceAllowed) {
index++;
} else {
break;
}
} else {
spaceAllowed = false;
// Read signs
if(isSign(letter)) {
if(signAllowed) {
signAllowed = false;
if(letter == '-') {
multiplier = -1;
}
index++;
} else {
break;
}
} else {
if(isNumber(letter)) {
// Mark beginning of numbers
startIndex = index;
endIndex = index;
scanNumber = true;
index++;
} else {
break;
}
}
}
}
}
if(startIndex >=0 && endIndex >=0) {
result = readNumber(str, startIndex, endIndex, multiplier);
}
return result;
}
private int readNumber(String text, int startIndex, int endIndex, int multiplier) {
int result = 0;
int power = endIndex - startIndex;
int i = startIndex;
while(i <= endIndex && !isMax(result)) {
int digit = text.charAt(i)-'0';
result += multiplier * (digit * (Math.pow(10,power--)));
i++;
}
return result;
}
private boolean isMax(int number) {
return (number == Integer.MAX_VALUE || number == Integer.MIN_VALUE);
}
private boolean isSpace(char character) {
return (character == ' ');
}
private boolean isNumber(char character) {
return (character >= '0' && character <= '9');
}
private boolean isSign(char character) {
return (character == '+' || character <= '-');
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment