[Solved] Get last “ordered” number [closed]


Here’s working code. Although I don’t like just giving you the answer. This is something you have to practice and learn how to do on your own. Take the time to understand what I did. Also, this solution can be improved a lot, just something that I did quickly and works.

The algorithm in action:

function calc() {
  //Get the number in the text input
  var nbr = parseInt(document.getElementById("number").value, 10);

  //Loop starting from the top
  for (var i = nbr; i > 0; i--) {
    if (isOrderedNumber(i)) {
      document.getElementById("result").innerText = i;
      return;
    }
  }
  document.getElementById("result").innerText = "None found";
}

function isOrderedNumber(number) {
  var digits = number.toString().split('');
  //Loops in the digits of the number
  for (var i = 0; i < digits.length - 1; i++) {
    //Check if the current number+1 is not equal to the next number.
    if (parseInt(digits[i]) + 1 !== parseInt(digits[i + 1])) {
      return false;
    }
  }

  return true;
}
<input id="number" type="text" />
<button onclick="calc()">Find last ordered number</button>
<br/>
<br/>
<span id="result"></span>

In you case, instead of using html element you would receive “nbr” by parameter instead and would return the value instead of putting the value in the html element. Ask if you have any questions on how this works.

solved Get last “ordered” number [closed]