Created
January 21, 2019 14:55
-
-
Save sunny-b/c901fcf3037b5cec027d3fe305bfd9a0 to your computer and use it in GitHub Desktop.
String to Integer Solution
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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