A *unique number* can be defined as a positive integer without leading zeros, in which each digit occurs only once (no duplicate digit). There can be various methods to detect whether or not a given positive integer is a unique number or not. I won’t be discussing methods which requires the number to be converted into a string as that would be inefficient in terms of space and time.

The approach which I am going to demonstrate in this post would use a boolean array of size ten to keep track for each of the possible ten digits. The idea is to extract digits of the number one by one, check the digit against the array to ascertain whether or not the extracted digit has already been encountered before and hence determine if the number is a unique number or not.

The java program to implement the above mentioned logic for unique number is as follows:

class UniqueNumber{
public static boolean isUniqueNumber( int n ){
boolean unique[] = new boolean[ 10 ];
int digit;
for( int temp=n; temp>0; temp/=10 ){
digit=temp%10;
if( unique[digit] ) return false;
else unique[digit]=true;
}
return true;
}
public static void main( String args[] ){
System.out.println(isUniqueNumber(1234)); //1234 is a unique number
System.out.println(isUniqueNumber(12342));//12342 is not a unique number
}
}

The output of the above program to ascertain the unique number would be as follows:

true
false

The boolean array *unique* is of size ten so as to store the status of occurrence of any of the ten possible digits. The function isUniqueNumber() would return false as soon as a repeated digit is encountered.

### Like this:

Like Loading...