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.

Javascript
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)


JavaScript Program to Check Whether a Number is a Duck Number

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
  • Recursive Method to check duck number

Similar Reads

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....

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....