-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstringToInteger.js
44 lines (37 loc) · 1.17 KB
/
stringToInteger.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
// string to integer
// Given a string, convert it to a integer.
// @param: str: a string
// @return: an integer
const isIntString = (str) => {
const charCode = str.charCodeAt()
if (charCode >= '0'.charCodeAt() && charCode <= '9'.charCodeAt()) return true
return false
}
const strToNum = (str) => (str.charCodeAt() - '0'.charCodeAt())
const stringToInteger = (str) => {
let start = 0, sig = 1
if (str[0] === '-') { start = 1, sig = -1 }
let number = 0
for (let i = start; i < str.length; i++) {
const item = str[i];
if (!isIntString(item)) throw Error('not a integer string')
const itemNum = strToNum(item)
number = number * 10 + itemNum
}
return number * sig
}
console.log(stringToInteger('123'))
console.log(stringToInteger('-3123'))
console.log(typeof stringToInteger('-3123'))
console.log(stringToInteger('121aaa=222'))
/*
const arr = str.split('')
arr.forEach((item, index) => {
if (index < start) return
if (!isIntString(item)) throw Error('not a integer string')
itemNum = strToNum(item)
number = number * 10 + itemNum
});
// foreach 无 break、continue,当 return 跳过本次循环进行下一次循环
// 不如直接 for 循环
*/