this is a problem on CodeWars, this code runs with me but on the site doesn't work and gives me this message
test
expected -1 to equal 414
,I have a successful code that runs on codewars but I want to know the problem in this code, the problem is
Create a function that takes a positive integer and returns the next bigger number that can be formed by rearranging its digits. For example:
nextBigger(num: 12) // returns 21
nextBigger(num: 513) // returns 531
nextBigger(num: 2017) // returns 2071
function nextBigger(n) {
//your code here
function equal(arr) {
let count = 0;
for (let i = 0; i < arr.length; i ) {
if (arr[i] == arr[i 1]) count ;
if (count == arr.length - 1) return true;
}
return false;
}
/* function noHope(arr) {
let count = 0;
for (let i in arr) {
if (arr[i] == arr[i 1]) count ;
}
if (count == arr.length - 1) return true;
else return false;
} */
let str = n.toString();
let arr = str.split("");
let revArr = arr.reverse();
let temp = 0;
for (let i = 0; i < arr.length; i ) {
if (revArr[i] > revArr[i 1]) {
temp = revArr[i];
revArr[i] = revArr[i 1];
revArr[i 1] = temp;
break;
} else if ((arr.length = 1 || arr.equal()) /* || arr.noHope */ ) {
return -1;
}
}
return parseInt(revArr.reverse().join(""));
}
console.log(nextBigger(12));
console.log(nextBigger(531));
console.log(nextBigger(2017));
console.log(nextBigger(414));
console.log(nextBigger(45222));
console.log(nextBigger(111));
console.log(nextBigger(8));
CodePudding user response:
You had two problems.
1) You were setting arr.length
to 1
instead of comparing it (=
vs ==
).
if ((arr.length = 1 || arr.equal()) /* || arr.noHope */ )
should be
if ((arr.length == 1 || arr.equal()) /* || arr.noHope */ )
2) You were attempting to call equal()
as a method of arr
, when you should have used arr
as a parameter.
if ((arr.length == 1 || arr.equal()) /* || arr.noHope */ )
should be
if ((arr.length == 1 || equal(arr)) /* || arr.noHope */ )
function nextBigger(n) {
//your code here
function equal(arr) {
let count = 0;
for (let i = 0; i < arr.length; i ) {
if (arr[i] == arr[i 1]) count ;
if (count == arr.length - 1) return true;
}
return false;
}
/* function noHope(arr) {
let count = 0;
for (let i in arr) {
if (arr[i] == arr[i 1]) count ;
}
if (count == arr.length - 1) return true;
else return false;
} */
let str = n.toString();
let arr = str.split("");
let revArr = arr.reverse();
let temp = 0;
for (let i = 0; i < arr.length; i ) {
if (revArr[i] > revArr[i 1]) {
temp = revArr[i];
revArr[i] = revArr[i 1];
revArr[i 1] = temp;
break;
} else if ((arr.length == 1 || equal(arr)) /* || arr.noHope */ ) {
return -1;
}
}
return parseInt(revArr.reverse().join(""));
}
console.log(nextBigger(12));
console.log(nextBigger(531));
console.log(nextBigger(2017));
console.log(nextBigger(414));
console.log(nextBigger(45222));
console.log(nextBigger(111));
console.log(nextBigger(8));