Created
July 3, 2020 00:08
-
-
Save RP-3/8a225bcce360b7ea759fa9a281bff88a to your computer and use it in GitHub Desktop.
This file contains hidden or 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
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