Unique Number in JAVA

Unique Number

Unique Number : A number is said to be a Unique number if it is a positive integer (without leading zeros) with no duplicate digits.

For example : 7, 135, 214 are all unique numbers whereas 33, 3121, 300 are not.

Input     : 142
Output  : It is a Unique Number

Input     :0125
Output  : It is not a Unique Number

Input     : 131
Output  : It is not a Unique Number

Algorithm and Program given below :-

Algorithm :-
  • Input number as a string
  • Store the length of the string in a variable
  • Using if statement first check if at 1st position (i.e. at 0th position of the string) '0' is present or not
  • If '0' is present than display "Number is not Unique"
  • Else using for loop extract each character and store it in an Array by converting the character into integer using type cast operator
  • After storing all the digits in the array
  • Use another for loops to check whether the number contains any duplicate digits.
  • If duplicate digits are found than display "Number is not Unique"
  • Else display "Number is Unique"
  • Compile and run the program

Program :-

import java.io.*;
import java.util.*;
class Unique
{
    public static void main(String args[])
    {
        Scanner in = new Scanner(System.in);
        int ar[]=new int[100];
//array for storing and comparing digits
        int i,j,k=0,a=0,l;
        String str;
        char ch;
        System.out.println("Enter Number ");
        str= in.nextLine();
//Input number as a string
        l= str.length();
// storing length of string
        if(str.charAt(0)=='0')
// if 0 is leading the number
        {
            System.out.println("It is not a Unique Number : " +str);
        }
        else
        {
            for(i=0;i<l;i++)
            {
                ch= str.charAt(i);
                ar[a]=(int)ch;
//storing each digit of the number
                a++;
            }
            for(i=0;i<(a-1);i++)
            {
                for(j=i;j<(a-1);j++)
                {
                    if(ar[i]==ar[j+1])
// comparing digits
                    {
                        k=1;
// if the digit are same than changing value of k to 1
                        break;
//using break statement to jump out of inner for loop
                    }
                }
                if(k==1)
                {
                    break;
//using break statement to jump out of outer for loop
                }
            }
            if(k==1)
// if k is equal to 1
            {
                System.out.println("It is not a Unique Number : " +str);
            }
            else
            {
                System.out.println("It is a Unique Number : "+str);
            }
        }
    }
// end of main method
} // end of class



Program Video : Watch now




All the Best :)
Keep Learning :)

Comments

Popular posts from this blog

Frequency of each digit of a number in Java

Trimorphic Number in JAVA

Tri-Automorphic Number in JAVA