-
Notifications
You must be signed in to change notification settings - Fork 0
/
08-NextGrowthNumber.js
64 lines (55 loc) · 1.05 KB
/
08-NextGrowthNumber.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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
const n = readline();
console.error(n)
console.log(findNextGrowth(n));
function findNextGrowth(str) {
let s = str[0]
let isChange = false
for (let i = 1; i < str.length; i++) {
if (str[i] < s[i - 1]) {
s += s[i - 1]
isChange = true
} else if (str[i] > s[i - 1] && isChange) {
s += s[i - 1]
} else {
s += str[i]
}
}
if (!isChange) {
let n = next(str)
while (!isGrowing(n)) {
n = next(n)
}
return n
}
return s
}
function next(s) {
let flag = true
let result = ''
for (let i = s.length - 1; i >= 0; i--) {
if (flag) {
if (s[i] === '9') {
result = '0' + result
flag = true
} else {
result = String.fromCharCode(s.charCodeAt(i) + 1) + result
flag = false
}
} else {
result = s.slice(0, i + 1) + result
break
}
}
if (flag) {
result = '1' + result
}
return result
}
function isGrowing(s) {
for (let i = 1; i < s.length; i++) {
if (s[i] < s[i - 1]) {
return false
}
}
return true
}