Unique Digit Number in Java
A unique digit number is a positive integer (without leading zeroes) with no duplicate digits. For example: 7, 135, 214 are all unique digit numbers, whereas 33, 3121, 300 are not unique digit numbers.
Given two positive integers m and n, where m < n, write a Java program to determine how many unique digit numbers are there in the range between m and n (both inclusive) and display them.
The input consists of two positive integers m and n where both m and n should be < 30000. You are required to display the number of unique digit numbers in the specified range along with their values in the format specified below:
Test your program for the following data and some random data.
Example 1:
INPUT:
m = 100
n = 120
OUTPUT:
THE UNIQUE DIGIT NUMBERS ARE:
102, 103, 104, 105, 106, 107, 108, 109, 120
FREQUENCY OF UNIQUE DIGIT NUMBERS: 9
Example 2:
INPUT:
m = 2505
n = 2525
OUTPUT:
THE UNIQUE DIGIT NUMBERS ARE:
2506, 2507, 2508, 2509, 2510, 2513, 2514, 2516, 2517, 2518, 2519
FREQUENCY OF UNIQUE DIGIT NUMBERS: 11
Example 3:
INPUT:
m = 2520
n = 2529
OUTPUT:
THE UNIQUE DIGIT NUMBERS ARE:
NIL
FREQUENCY OF UNIQUE DIGIT NUMBERS: 0
class Unique{
public static void main(String[] args){
Scanner in = new Scanner(System.in);
System.out.print("m = ");
int m = Integer.parseInt(in.nextLine());
System.out.print("n = ");
int n = Integer.parseInt(in.nextLine());
if(m >= n || m > 30000 || n > 30000){
System.out.println("INVALID INPUT");
return;
}
int f = 0;
System.out.println("THE UNIQUE DIGIT NUMBERS ARE:");
for(int i = m; i <= n; i++){
if(isUnique(i)){
if(f == 0)
System.out.print(i);
else
System.out.print(", " + i);
f++;
}
}
if(f == 0)
System.out.print("NIL");
System.out.println("\nFREQUENCY OF UNIQUE DIGIT NUMBERS: " + f);
}
public static boolean isUnique(int n){
for(int i = 0; i <= 9; i++){
int c = 0;
for(int j = n; j != 0; j /= 10){
int d = j % 10;
if(i == d)
c++;
}
if(c > 1)
return false;
}
return true;
}
}
Comments
Post a Comment