Skip to content

Instantly share code, notes, and snippets.

@sunny-b
Created January 21, 2019 14:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sunny-b/c901fcf3037b5cec027d3fe305bfd9a0 to your computer and use it in GitHub Desktop.
Save sunny-b/c901fcf3037b5cec027d3fe305bfd9a0 to your computer and use it in GitHub Desktop.
String to Integer Solution
const WHITESPACE = ' ';
const NEGATIVE_SIGN = '-';
const POSITIVE_SIGN = '+';
const INTEGER_REGEX = /[0-9]/;
const MAX_INTEGER = (2**31) - 1;
const MIN_INTEGER = -(2**31);
function myAtoi(str) {
const strIntArray = [];
let isNegative = false;
let resultVal = 0;
let idx = 0;
while (str[idx] === WHITESPACE) {
idx++;
}
if (invalidChar(str[idx])) {
return 0;
}
if (isSign(str[idx])) {
isNegative = str[idx] === NEGATIVE_SIGN;
idx++;
}
while (isInteger(str[idx])) {
strIntArray.unshift(str[idx]);
idx++;
}
for (let i = 0; i < strIntArray.length; i++) {
let num = Number(strIntArray[i]);
num *= 10**i;
resultVal += num;
}
if (isNegative) {
resultVal = -resultVal;
}
// If result value is less than min, reassign to min
resultVal = Math.max(resultVal, MIN_INTEGER);
// If result value is greater than max, reassign to max.
resultVal = Math.min(resultVal, MAX_INTEGER);
return resultVal;
}
function invalidChar(char) {
return !isInteger(char) && !isSign(char);
}
function isSign(char) {
return char === POSITIVE_SIGN || char === NEGATIVE_SIGN
}
function isInteger(char) {
return INTEGER_REGEX.test(char);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment