Duck Number in JAVA
Duck Number
Duck Number : A Duck number is a number which has zeroes present in it, but there should be no zero present in the beginning of the number.
For example : 3210, 7056, 8430709 are all duck numbers, whereas 08237, 04309, 2357,1253 etc are not.
Input : 50401
Output : It is a Duck Number
Input : 04208
Output : It is not a Duck Number
Input : 4231
Output : It is not a Duck Number
Algorithm :-
- Input a number in a string variable
- In a variable find its length
- Using if statement check if it has 0 at 1st position (i.e. at 0th position in string) using "charAt"
- If it has 0 than display "It is not a duck number"
- Else using for loop extract each character from 2nd position (i.e. at 1st position of string).
- Now check if the character is '0' or not
- If it is '0' than use break statement and display "It is Duck Number"
- Else display "It is not a Duck Number"
Program :-
import java.io.*;
import java.util.*;
class Duck
{
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
String str;
char ch;
int k=0,l,i;
System.out.println("Enter Number ");
str= in.nextLine(); // Input number as a String
l= str.length(); // storing length of the number
if(str.charAt(0)=='0') // if at 0th position 0 is present
{
System.out.println("It is not a Duck Number "+str); // print number is not duck no.
}
else
{
for(i=1;i<l;i++)
{
ch=str.charAt(i); //extracting each character from 1st position
if(ch=='0') // if is found at any position
{
k=1; //defining value of k=1
break;
}
}
if(k==1)
{
System.out.println("It is a Duck Number : "+str); //printing duck number
}
else
{
System.out.println("It is not a Duck Number : "+str); // printing not a duck no.
}
}
} // end of main method
} // end of class
import java.util.*;
class Duck
{
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
String str;
char ch;
int k=0,l,i;
System.out.println("Enter Number ");
str= in.nextLine(); // Input number as a String
l= str.length(); // storing length of the number
if(str.charAt(0)=='0') // if at 0th position 0 is present
{
System.out.println("It is not a Duck Number "+str); // print number is not duck no.
}
else
{
for(i=1;i<l;i++)
{
ch=str.charAt(i); //extracting each character from 1st position
if(ch=='0') // if is found at any position
{
k=1; //defining value of k=1
break;
}
}
if(k==1)
{
System.out.println("It is a Duck Number : "+str); //printing duck number
}
else
{
System.out.println("It is not a Duck Number : "+str); // printing not a duck no.
}
}
} // end of main method
} // end of class
All the Best :)
Comments
Post a Comment