-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathnext_bigger_number_with_the_same_digits.js
More file actions
51 lines (49 loc) · 2.79 KB
/
next_bigger_number_with_the_same_digits.js
File metadata and controls
51 lines (49 loc) · 2.79 KB
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
/******************************************************************************************
* CODEWARS NEXT BIGGER NUMBER WITH SAME DIGITS CHALLENGE *
* *
* Problem Statement *
* You have to create a function that takes a positive integer number and returns the next*
* bigger number formed by the same digits: *
* *
* Test Cases *
* Input 1: 12 *
* Output 1: 21 *
* *
* Input 2: 513 *
* Output 2: 531 *
* *
* Input 3: 2017 *
* Output 3: 2071 *
* *
* If no bigger number can be composed using those digits, return -1 *
* *
* Input 4: 9 *
* Output 4: -1 *
* *
* Input 5: 111 *
* Output 5: -1 *
* *
*****************************************************************************************/
function nextBigger(n) {
let flag = true;
let N = String(n);
for (let i = 0; i < N.length - 1; i++) {
if (+N[i] >= +N[i + 1]) {
flag = true;
} else {
flag = false;
break;
}
}
if (flag === true) return -1;
let ans = 0;
let s2 = String(n).split("").sort().join("");
for (let i = n + 1; ; i++) {
let s = String(i).split("").sort().join("");
if (s2 == s) {
ans = i;
break;
}
}
return ans;
}