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 requirements up front.
Update (2015-02-10):
The signature of the C++ function had been updated. If you still see your function signature accepts a const char * argument, please click the reload button to reset your code definition.
spoilers alert… click to show requirements for atoi.
public class Solution {
public int myAtoi(String str) {
// 1. null or empty string
if (str == null || str.length() == 0) return 0;
// 2. whitespaces
str = str.trim();
// 3. +/- sign
boolean positive = true;
int i = 0;
if (str.charAt(0) == '+') {
i++;
} else if (str.charAt(0) == '-') {
positive = false;
i++;
}
// 4. calculate real value
double tmp = 0;
for ( ; i < str.length(); i++) {
int digit = str.charAt(i) - '0';
if (digit < 0 || digit > 9) break;
// 5. handle min & max
if (positive) {
tmp = 10*tmp + digit;
if (tmp > Integer.MAX_VALUE) return Integer.MAX_VALUE;
} else {
tmp = 10*tmp - digit;
if (tmp < Integer.MIN_VALUE) return Integer.MIN_VALUE;
}
}
int ret = (int)tmp;
return ret;
}
}
Java2
class Solution {
public int myAtoi(String str) {
str = str.trim();
int retVal = 0;
int startIndex = 0;
int sign = 1;
if(str.equals("")) {
return 0;
}
startIndex = str.charAt(0) == '-' || str.charAt(0) == '+' ? 1 : 0;
sign = str.charAt(0) == '-' ? -1 : 1;
for(int i = startIndex ; i < str.length() ; i++) {
char c = str.charAt(i);
if('0' <= c && c <= '9') {
if(retVal > (Integer.MAX_VALUE - (c - '0')) / 10)
return sign > 0 ? Integer.MAX_VALUE : Integer.MIN_VALUE;
retVal = retVal * 10 + (c - '0');
} else {
break;
}
}
return sign * retVal;
}
}
JS
/**
* @param {string} str
* @return {number}
*/
var myAtoi = function(str) {
str = str.trimLeft(); // remove whitespace from beginning of string
if (!/[\d+-]/.test(str[0])) return 0; // if first character is not +,- or a digit
const number = Number(str.match(/[+-]?\d*/)); // regex means: optional(+,-) follows by zero (case " + 514 " => expect 0) or more digits
if (Number.isNaN(number)) return 0; // invalid integral number. eg: " + 514" => expect 0 (Number('+') => NaN)
const MAX_INT = 2 ** 31 - 1;
const MIN_INT = - (2 ** 31);
if (number < MIN_INT) return MIN_INT;
if (number > MAX_INT) return MAX_INT;
return number;
};