Skip to content

Instantly share code, notes, and snippets.

@RP-3
Created July 3, 2020 00:08
Show Gist options
  • Save RP-3/8a225bcce360b7ea759fa9a281bff88a to your computer and use it in GitHub Desktop.
Save RP-3/8a225bcce360b7ea759fa9a281bff88a to your computer and use it in GitHub Desktop.
var myAtoi = function(str) {
str = str.trim();
if(!str.length) return 0;
let negative = false;
const chars = [];
if(!str[0].match(/[0-9\+\-]/)) return 0;
let i = 0;
if(str[0] === '-'){
negative = true;
i++;
}
else if(str[0] === '+') i++;
for(null; i<str.length; i++){
if(str[i].match(/[0-9]/)) chars.push(str[i]);
else break;
}
if(!chars.length) return 0;
const numStr = chars.join('');
const num = parseInt(numStr); // because I can't stomach doing even more work
const maxInt = (1<<30)-1 + (1<<30);
if(num > maxInt) return negative ? (-maxInt-1) : maxInt;
if(negative) return -num;
return num;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment