logo CodeStepByStep logo

digitsSorted

Language/Type: JavaScript recursion string

Write a recursive function named digitsSorted that takes an integer as a parameter and returns true if the digits of the integer are sorted and false otherwise. The digits must be sorted in non-decreasing order (i.e. increasing order with duplicate digits allowed) when read from left to right. An integer that consists of a single digit is sorted by definition. The function should be also able to handle negative numbers. Negative numbers are also considered sorted if their digits are in non-decreasing order.

The following table shows several calls to your function and their expected return values:

Call Value Returned
digitsSorted(0) true
digitsSorted(2345) true
digitsSorted(-2345) true
digitsSorted(22334455) true
digitsSorted(-5) true
digitsSorted(4321) false
digitsSorted(24378) false
digitsSorted(21) false
digitsSorted(-33331) false

Constraints:

  • Do not use any loops; you must use recursion.
  • Do not declare any global variables.
  • Do not use arrays.
  • You may define other "helper" functions if you like; they are subject to these same constraints.

Note: Because JavaScript integers are number types, dividing two integers which do not divide evenly returns the decimal value of the result instead of an integer (for example, 1 / 2 results in 0.5, not 0). Use parseInt(a / b) to parse the result into an integer if needed to solve this problem.

Function: Write a JavaScript function as described, not a complete program.

You must log in before you can solve this problem.

Log In

Need help?

Stuck on an exercise? Contact your TA or instructor.

If something seems wrong with our site, please

Is there a problem? Contact us.