Duck numbers are special numbers that occur when a number has the digit '0' in it, but the '0' is not the first digit. numbers require the digit '0' to appear in the number, but not as the first digit.
JavaScript provided several methods to check whether a number is a duck number which are as follows:
Table of Content
Iterative Approach
This method first converts the number into a string to check whether that number is a duck number or not. It simply skips zeros at the start of the string, if there are any. This code checks if the input, after handling leading zeros, contains the digit '0'. If 0 is present in that string, it is consider as a Duck Number, otherwise, it is not.
Example: Duck Number Detection in JavaScript involves checking whether a given number is a "duck number" by ignoring leading zeros and then searching for the presence of a zero digit.
function duckNumber(input) {
let i = 0, length = input.length;
for (i; i < length && input[i] == '0'; i++) {
// Loop to ignore leading 0s
}
// Check remaining digits
for (i; i < length; i++) {
if (input[i] == '0') {
return true;
}
}
return false;
}
// Example
let num = "0123";
if (duckNumber(num))
console.log("It is a duck number");
else
console.log("It is not a duck number");
Output
It is not a duck number
Time Complexity: O(n)
Space Complexity: O(1)
Recursive Method to check duck number
This method first convert the number into string to check weather that number is duck number or not. It simply skips zeros at the start of the string, if there are any. It uses a recursive approach to traverse through the digits, printing whether the number is a Duck Number or not.
Example: To determining Duck numbers in JavaScript by ignoring leading zeros and then checking for the presence of a zero digit.
function isDuckNumber(num, index = 1) {
let str = num.toString();
if (index === str.length) {
console
.log(`${num} is not a Duck Number.`);
return;
}
if (str[index] === '0') {
console
.log(`${num} is a Duck Number.`);
return;
}
isDuckNumber(num, index + 1);
}
// Example
const num = 23;
isDuckNumber(num);
Output
23 is not a Duck Number.
Time Complexity: O(n)
Space Complexity: O(n)