Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Finding tidy numbers - JavaScript
A tidy number is a number whose digits are in non-decreasing order. We are required to write a JavaScript function that takes in a number and checks whether its a tidy number or not.
For example:
489 is a tidy number 234557 is also a tidy number 34535 is not a tidy number
Understanding Tidy Numbers
In a tidy number, each digit should be less than or equal to the next digit when reading from left to right. For instance, in 234789, we have 2 ? 3 ? 4 ? 7 ? 8 ? 9, making it tidy.
Method 1: Using Recursion
This approach processes digits from right to left, comparing each digit with the previous one:
const num = 234789;
const isTidy = (num, last = 10) => {
if(num){
if(num % 10 > last){
return false;
};
return isTidy(Math.floor(num / 10), (num % 10));
};
return true;
};
console.log(isTidy(num));
console.log(isTidy(34535));
console.log(isTidy(489));
true false true
Method 2: Using String Conversion
Convert the number to a string and compare adjacent characters:
const isTidyString = (num) => {
const str = num.toString();
for(let i = 0; i str[i + 1]){
return false;
}
}
return true;
};
console.log(isTidyString(234789));
console.log(isTidyString(34535));
console.log(isTidyString(111223));
true false true
Method 3: Using Array and every()
Convert to digit array and use the every() method for validation:
const isTidyArray = (num) => {
const digits = num.toString().split('').map(Number);
return digits.every((digit, index) =>
index === 0 || digit >= digits[index - 1]
);
};
console.log(isTidyArray(234789));
console.log(isTidyArray(987654));
console.log(isTidyArray(112233));
true false true
Comparison
| Method | Time Complexity | Space Complexity | Readability |
|---|---|---|---|
| Recursion | O(d) | O(d) | Medium |
| String Loop | O(d) | O(d) | High |
| Array + every() | O(d) | O(d) | High |
Where d is the number of digits
Conclusion
All three methods effectively check for tidy numbers. The string conversion approach offers the best balance of readability and performance, while the array method provides a more functional programming style.
