forked from tangweikun/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
60 lines (45 loc) · 1.15 KB
/
index.ts
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
// HELP:
export const isAdditiveNumber = (num: string) => {
// The first two numbers
let a = 0
let b = 0
// Length of the first number
for (let i = 0; i < num.length / 2; i++) {
// Last digit of the first number
const _a = num.charCodeAt(i) - 48
// Second number starts with zero?
const zero = num.charCodeAt(i + 1) === 48
// Update the first number
a = a * 10 + _a
// Reset the second number
b = 0
// Length of the second number
for (var j = 1; j <= num.length / 2; j++) {
// Invalid number
if (zero && j > 1) continue
// Update the second number
b = b * 10 + (num.charCodeAt(i + j) - 48)
// Validate
if (validate(a, b, num)) return true
}
}
return false
}
const validate = function(a: number, b: number, target: string) {
const limit = target.length
let str = '' + a + b
// No place for the third number
if (str.length >= limit) return false
// Generate sequence
while (str.length < limit) {
// Append number
const c = a + b
str += c
// Validate
if (str === target) return true
// Swap
a = b
b = c
}
return false
}