Skip to content

Instantly share code, notes, and snippets.

@sAVItar02
Created November 12, 2024 03:57
Show Gist options
  • Save sAVItar02/456d8c1d208bd289456f4a3643aa77d7 to your computer and use it in GitHub Desktop.
Save sAVItar02/456d8c1d208bd289456f4a3643aa77d7 to your computer and use it in GitHub Desktop.
String to integer (atoi)
/**
* @param {string} s
* @return {number}
*/
var myAtoi = function(s) {
let num = 0;
let isNegative = false;
let numString = "";
let hasEncountered = false;
let hasBeenPositive = false;
for(let i=0; i<s.length; i++) {
if(hasEncountered) {
if(s[i].charCodeAt(0) < 48 || s[i].charCodeAt(0) > 57) break;
}
if(s[i].charCodeAt(0) < 32 || s[i].charCodeAt(0) > 57 || s[i].charCodeAt(0) == 46) break;
if(!hasEncountered && s[i].charCodeAt(0) == 32) {
if(hasBeenPositive || isNegative) break;
continue;
}
if(!hasEncountered && s[i].charCodeAt(0) == 43) {
if(isNegative || hasBeenPositive) break;
hasBeenPositive = true;
continue;
}
if(!hasEncountered && s[i].charCodeAt(0) == 45) {
if(hasBeenPositive || isNegative) break;
isNegative = true;
continue;
}
if(s[i].charCodeAt(0) >= 48 && s[i].charCodeAt(0) <= 57) hasEncountered = true;
numString += s[i];
}
if(numString.length != 0) {
if(isNegative) num = numString * 1 * -1;
else num = numString * 1;
}
if(num <= -2147483648) return -2147483648;
if(num >= 2147483647) return 2147483647;
return num;
};
// run a loop and for each character, check if any of the question rules have been broken
// if the character at the start (ignoring the whitespace) is negative then make the isNegative flag true
// if the character at the start (ignoring the whitespace) is positive then make the hasBeenPositive flag true
// if at any time the number hasBeenPositive or Negative return 0
// else, if the number is negative return -num else return num
// Time: O(n)
// Space: O(1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment