Subscribe Us

Duck Number In Java

Duck Number In Java


Java Program To Check Duck Numbers

A Duck number is a positive number which has zeroes present in it.
Example: 120, 1024, 102030 are all Duck numbers.
Note : A Numbers with only leading 0s is not considered as Duck Number.
Example:
Numbers Like 007 or 001 are Not Considered as Duck Numbers.
To check if a number is a Duck Number or not in Java
you can use the following algorithm:
  1. Read the input number.
  2. Initialize a variable count to 0.
  3. While num is not equal to 0, perform the following steps:
    • Get the last digit of the num by using the modulo operator (%).
    • if last digit = 0 then increase count by 1
    • Divide the num by 10 to remove the last digit.
  4. If count = '0' the number is a Duck Number.
  5. If count not = '0' the number is Not a Duck Number.

Note that this implementation assumes that the input number is a positive integer. You may need to add additional checks for negative numbers or other cases depending on your requirements.

Here is an example implementation in Java

Source Code

//Java Program To Check Duck Numbers - Method One
import java.util.*;
public class DuckNumber 
 {
  public static void main(String args[])
   {
     Scanner in = new Scanner(System.in);
     int num , Rd, count = 0 ;
     System.out.print("Enter a Number To Check : ");
     num=in.nextInt();
     while(num!=0)
      {
        Rd = num % 10 ;
        if(Rd==0)
         count++;
        num= num / 10 ; 
      }
     if(count>=1)
      System.out.print("It is a Duck Number .");
     else
      System.out.print("It is Not a Duck Number .");
   }
 }

Output

Sample Input :
Enter a Number To Check : 1024
Sample Output:
It is a Duck Number

Sample Input :
Enter a Number To Check : 123
Sample Output:
It is Not a Duck Number

//Java Program To Check Duck Numbers - Method Two
import java.util.*;
public class DuckNumber 
 {
  public static void main(String args[])
   {
     Scanner in = new Scanner(System.in);
     int num , Rd;
     boolean check=false;
     System.out.print("Enter a Number To Check : ");
     num=in.nextInt();
     while(num!=0)
      {
        Rd = num % 10 ;
        if(Rd==0)
         {
           check=true;
           break;
         }
        num= num / 10 ; 
      }
     //if(check)
     if(check==true)
      System.out.print("It is a Duck Number .");
     else
      System.out.print("It is Not a Duck Number .");
   }
 }

Output

Sample Input :
Enter a Number To Check : 1008
Sample Output:
It is a Duck Number

Sample Input :
Enter a Number To Check : 156
Sample Output:
It is Not a Duck Number

Looping Related Programs