-
Notifications
You must be signed in to change notification settings - Fork 0
/
next-bigger-number-with-the-same-digits.js
59 lines (46 loc) · 1.69 KB
/
next-bigger-number-with-the-same-digits.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
/**
* http://www.codewars.com/kata/55983863da40caa2c900004e/
*
Description:
You have to create a function that takes a positive integer number and returns the next bigger number formed by the same digits:
*/
let tests = require('./lib/framework.js');
let Test = tests.Test, describe = tests.describe, it = tests.it, before = tests.before, after = tests.after;
function replace(array, replace, startIndex) {
var copy = array.slice(0);
Array.prototype.splice.apply(copy, [startIndex, replace.length].concat(replace));
return copy;
}
function nextBigger(n) {
var digits = n.toString().split('').map(x => parseInt(x)), i, j, ph, num, rest, ret, min = 9, minIndex = 0;
for (i = digits.length - 1; i >= 0; i--) {
if (i === digits.length - 1) {
continue;
}
if (digits[i] < digits[i + 1]) {
num = digits[i];
rest = digits.slice(i + 1);
for (j = 0; j < rest.length; j++) {
if (rest[j] > num && rest[j] < min) {
min = rest[j];
minIndex = j;
}
}
ph = num;
num = min;
rest[minIndex] = ph;
rest = [num].concat(rest.sort((a, b) => {
return a > b ? 1 : -1;
}));
digits = replace(digits, rest, i);
break;
}
}
ret = parseInt(digits.join(''));
return ret === n ? -1 : ret;
}
Test.assertEquals(nextBigger(12),21);
Test.assertEquals(nextBigger(513),531);
Test.assertEquals(nextBigger(2017),2071);
Test.assertEquals(nextBigger(414),441);
Test.assertEquals(nextBigger(144),414);