logo CodeStepByStep logo

digits_sorted

Language/Type: PHP recursion string return

Write a recursive function named digits_sorted 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 when 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
digits_sorted(0) true
digits_sorted(2345) true
digits_sorted(-2345) true
digits_sorted(22334455) true
digits_sorted(-5) true
digits_sorted(4321) false
digits_sorted(24378) false
digits_sorted(21) false
digits_sorted(-33331) false

Constraints:

  • Do not declare any global variables.
  • Do not use any loops; you must use recursion.
  • Do not use any auxiliary data structures (e.g. arrays) or strings to solve this problem.
  • You can declare as many primitive variables (e.g. integers) as you like.
  • You are allowed to define other "helper" functions if you like; they are subject to these same constraints.
Function: Write a PHP 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.