Skip to content

Commit

Permalink
add: 实现atoi函数
Browse files Browse the repository at this point in the history
  • Loading branch information
xldeng committed Feb 25, 2022
1 parent a2fcd78 commit 1820caa
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 1 deletion.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@
1. [最长公共前缀](https://github.com/dengshasha/algorithm-study/blob/master/string/longestCommonPrefix.js) || [leetcode地址](https://leetcode.com/problems/longest-common-prefix/submissions/)
2. [校验括号的合法性](https://github.com/dengshasha/algorithm-study/blob/master/string/validParentheses.js) || [leetcode地址](https://leetcode.com/problems/valid-parentheses/submissions/)
3. [在字符串中查找数组中的级联子串](https://github.com/dengshasha/algorithm-study/blob/master/string/substrWithConcatenation.js) || [leetcode地址](https://leetcode.com/problems/substring-with-concatenation-of-all-words/submissions/)
4. [实现atoi函数](https://github.com/dengshasha/algorithm-study/blob/master/string/strToInteger.js) || [leetcode地址](https://leetcode.com/problems/string-to-integer-atoi/submissions/)

### 数组
1. [数组各项,除该项外累乘的结果](https://github.com/dengshasha/algorithm-study/blob/master/array/productArrayExceptSelf.js) || [leetcode地址](https://leetcode.com/problems/product-of-array-except-self/submissions/)
Expand Down
2 changes: 1 addition & 1 deletion index.html
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,6 @@
<title>Document</title>
</head>
<body>
<script src="slideWindow/substrWithConcatenation.js"></script>
<script src="string/strToInteger.js"></script>
</body>
</html>
25 changes: 25 additions & 0 deletions string/strToInteger.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
/**
* @param {string} s
* @return {number}
*/
var myAtoi = function(s) {
let left = 0, right = 0
let sTrim = s.trim()
const MAX_INTERGER = Math.pow(2,31)
const MIN_INTERGER = -MAX_INTERGER
if(sTrim.length >= 2 && (sTrim[0] === '-' || sTrim[0] === '+') && /\d/.test(sTrim[1])) {
right++;
}
for(let i = 0; i < sTrim.length; i++) {
if(i === 0 && (sTrim[i] === '-' || sTrim[i] === '+')) continue;
if(!/\d/.test(sTrim[i])) break;
right++;
}
let value = Number(sTrim.substring(left, right));
if(value > MAX_INTERGER) return MAX_INTERGER
if(value < MIN_INTERGER) return MIN_INTERGER
return value
};

console.log(myAtoi('-42'))
console.log(myAtoi('-+42'))

0 comments on commit 1820caa

Please sign in to comment.