Wednesday, December 1, 2010

To find n digit unique number in java

import java.io.*;
class UniqueNo
{
long countDigits(long no)
{
long copy = no,count = 0;
while(copy!=0)
{
count++;
copy/=10;
}
return count;
}
boolean checkUnique(long n)
{
int nd = (int)countDigits(n);
long arr[] = new long[nd];
long copy = n;
int digit,term = 0;
while(copy!=0)
{
digit = (int)copy%10;
arr[term] = digit;
term++;
copy/=10;
}
for(int i = 0;i<nd-1;i++)
{
for(int j = i+1;j<nd;j++)
{
if(arr[i] == arr[j])
return false;
}
}
return true;
}
void main() throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter the value of n to find all n digit unique nos - ");
long n = Long.parseLong(br.readLine());
long count = 0;
for(long i = (long)Math.pow(10,n-1);i<=(long)Math.pow(10,n)-1;i++)
{
if(checkUnique(i)==true)
{
System.out.println(i);
count++;
}
}
System.out.println(" "+count+" unique nos have been generated.");
}
}

No comments: