Unique Number in Java

(Last Updated On: 01/02/2024)

In this blog, we will look at unique numbers, their importance in Java programming, and how they differ from other numbers. Join us as we explore the distinctive digit patterns and present concrete examples that highlight the value and appeal of unique number in Java.

What is a Unique Number in Java?

Positive integers with only distinct digits—i.e., digits that only occur once in the number—are referred to as unique numbers. In other words, a unique number doesn’t contain any digits that are repeated.

Unique Number Examples:

Let’s look at a few examples of unique numbers in Java to better understand their distinctive digit patterns. Think about the following:

Example 1: Number 4572

Each digit (4, 5, 7, and 2) only appears once in this situation. It is a unique number because of the distinctive digit pattern.

Example 2: Number 1029

Even though this number has four digits, it does not satisfy the requirement for uniqueness. The requirement for distinct digits is broken by the digit 1 appearing twice.

Example 3: Number 386541

 Each digit only appears once in this number, which illustrates the distinct digit pattern. It complies with the requirement for uniqueness in Java.

Steps to Check Unique Number in Java:

To check if a number is unique in Java, you can follow these steps:

  • Convert the number to a string: Start by using the Integer.toString() method to transform the number into a string. We can easily iterate over each digit thanks to this.
  • Create a boolean array: Set up a 10-element boolean array with the digits 0 through 9 as its initial values. We can keep track of how often each digit appears thanks to this array.
  • Iterate over each digit: To iterate through each character in the number’s string representation, use a loop. Use the Character.getNumericValue() method to change each character back to an integer.
  • Check for duplicate digits: Verify that the corresponding index in the boolean array is true for each digit. If it is, that indicates the digit is not unique because it has already happened. If so, give a false response.
  • Update the boolean array:  If the digit is not duplicated, update the corresponding index in the boolean array to true to mark its occurrence.
  • Return true: The number is unique if the loop ends with no duplicate digits being found. To show this, return true.

Algorithm for Checking Unique Numbers:

The following algorithm can quickly locate distinctive numbers in Java:

  • The first step is to represent the given number as a string. 
  • Set up a boolean array of size 10, which will contain the digits 0 through 9. 
  • Perform an iteration over each digit in the number’s string representation. 
  • Verify that the corresponding index in the boolean array is true for each digit. 
  • Return false if it isn’t since the number isn’t unique.
  • In the boolean array, change the corresponding index to true if the digit is unique. 
  • Return true to show that the number is unique after verifying all the digits. 
  • By keeping track of digit occurrences in a boolean array, this algorithm efficiently checks for unique numbers. 
  • It guarantees an optimized method for finding unique numbers in Java by only iterating over the digits once.

Know the Fibonacci series in Java here!

Methods for Finding Unique Numbers in Java

In Java, there are several methods for finding unique numbers. Here are two common approaches:

By Comparing Each Digit Manually

In the below code we will see how to find unique numbers in java by comparing each digit manually:

import java.util.Scanner; 
public class UniqueNumEx 
{ 
public static void main(String args[]) 
{ 
int r1, r2, number, n1, n2, count = 0; 
Scanner sc = new Scanner(System.in); 
System.out.print("Enter the number you want to check: "); 
//reading a number from the user 
number = sc.nextInt(); 
//num1 and num2 are temporary variable 
n1 = number; 
n2 = number; 
//iterate over all digits of the number 
while (n1 > 0) 
{ 
//detrmins the last digit of the number     
r1 = n1 % 10; 
while (n2 > 0) 
{ 
//finds the last digit 
r2 = n2 % 10; 
//comparing the last digit 
if (r1 == r2) 
{ 
//increments the count variable by 1     
count++; 
} 
//removes the last digit from the number 
n2 = n2 / 10; 
} 
//removes the last digit from the number 
n1 = n1 / 10; 
} 
if (count == 1) 
{ 
System.out.println("The number is unique."); 
} 
else 
{ 
System.out.println("The number is not unique."); 
} 
} 
}

Explanation of the code:

The given code is written in Java to check whether a number is unique or not. It takes an input number from the user and performs the following steps:

  • Initialize variables: The code initializes variables r1, r2, number, n1, n2, and count to hold different values during the program execution.
  • Read input: It prompts the user to enter a number and reads the input using the Scanner class.
  • Determine uniqueness: The code uses nested while loops to iterate over the digits of the number. It extracts the last digit (r1) from the first iteration and compares it with the last digit (r2) in subsequent iterations.
  • Count occurrences: If r1 matches r2, it increments the count variable. This count keeps track of the number of occurrences of the same digit within the number.
  • Check uniqueness: After completing the iteration, the code checks if the count is equal to 1. If so, it concludes that the number is unique. Otherwise, it determines that the number is not unique.
  • Display result: Finally, the code prints a message indicating whether the number is unique or not based on the comparison result.

This code helps identify unique numbers by comparing each digit with the rest of the digits in the number. If there is only one occurrence of each digit, the number is considered unique.

Check out our Java Online Compiler here!

Output:

Enter the number you want to check: 13985
The number is unique.

Using String

In the below code we will see how to find unique numbers in java by using string:

import java.util.*;  
    public class UniqueNumEx  
    {  
    public static void main(String args[] )  
    {  
    Scanner sc=new Scanner(System.in);  
    System.out.print("Enter the number you want to check:");  
    //reading an integer from the user  
    int number=sc.nextInt();  
    //converts integer data type into string  
    String str= Integer.toString(number);   
    //determines the length of the string  
    int length=str.length();  
    int flag=0, i, j;  
    //loop checks the digits are repeated or not  
    for(i=0;i<length-1;i++)  
    {  
    for(j=i+1;j<length;j++)  
    {  
    //comparing each digit, if digits are repeated the number is not unique       
    if(str.charAt(i)==str.charAt(j))   
    {   
    flag=1;  
    break;   
    }  
    }  
    }  
    //if flag is equal to zero the number is unique  
    if(flag==0)  
    System.out.println("The number is unique.");  
    else  
    System.out.println("The number is not unique.");  
    }  
    }  

Explanation of the code:

The provided Java code determines whether or not a number is unique. 

It creates a string out of the user’s input of an integer. Iterating through the string’s digits yields the string’s length. 

Each digit is compared to the other digits using nested for loops in the code. The flag variable is set to 1, indicating that the number is not unique if any two digits are discovered to be the same.

The code checks the value of the flag variable after the loops. If it remains 0, no duplicate digits were discovered, and the number is regarded as unique. In this instance, the message “The number is unique” is printed. 

Otherwise, it prints the message “The number is not unique” if the flag is set to 1, indicating that at least one repeated digit was discovered.

By comparing a number’s digits, this code offers a quick and easy way to determine whether it is unique. It can serve as a foundation for further improvements or be incorporated into a bigger program that needs uniqueness validation.

Output:

Enter the number you want to check:254865
The number is not unique.

Using Array

In the below code we will see how to find unique numbers in java by using array:

import java.util.Scanner; 
public class UniqueNumberEx 
{ 
//static method that checks the number is unique or not 
public static boolean isUniqueNum(int number)  
{ 
//count the number of digits in a number 
int digits = countDigits(number); 
//declaring and creating an array of digits 
int[] arr = new int[digits]; 
for(int i=0; i<digits; i++)  
{ 
//determines the last digits and adds it to the ith position 
arr[i] = (int)number%10; 
//removes the last digit 
number = number/10; 
} 
//compares array elements 
for(int i=0; i<digits; i++)  
{ 
for(int j=0; j<digits; j++)  
{ 
//returns true if both conditions are true     
if(i!=j && arr[i]==arr[j]) 
return false; 
} 
} 
return true; 
} 
public static int countDigits(int number)  
{ 
int count = 0; 
//executes until the condition becomes false 
while(number != 0)  
{ 
//increments the variable count by 1 
count++; 
//removes last digits 
number= number/10; 
} 
return count; 
} 
public static void main(String args[])  
{ 
//declare variables 
int number = 0; 
boolean res = false; 
//create Scanner class object to take input 
Scanner scan = new Scanner(System.in); 
System.out.print("Enter the number you want to check: "); 
//reading an integer from the user 
number = scan.nextInt(); 
//invoking the method and parsing the number to be check 
res = isUniqueNum(number); 
if(res) 
System.out.println(number +" is a unique number."); 
else 
System.out.println(number +" is not a unique number."); 
} 
}  

Explanation of the code:

The provided Java code verifies the uniqueness of a given number. It includes a static method called isUniqueNum that accepts an integer and returns a boolean value indicating whether the number is unique.

The code uses the countDigits method to first count the number of digits in the input before determining uniqueness. It then creates a digit array and populates it by repeatedly removing the last digit from the number.

Next, the code compares the digit pairs in the array. If any two digits are discovered to be identical, it returns false, indicating that the number is not unique. If not, it returns true if all of the digits are distinct.

In the main method, the code prompts the user to enter a number and calls the isUniqueNum method to check its uniqueness. Then, the program displays the result to the user.

This code provides a modular and efficient approach to determining the uniqueness of a number by extracting its digits and comparing them. It can be easily integrated into larger programs or used as a standalone uniqueness checker.

Output:

Enter the number you want to check: 1423
1423 is a unique number.

Real-World Applications and Use Cases

A. Data Validation and Error Handling

  • The processes used for data validation and error handling heavily rely on unique numbers. 
  • To ensure the avoidance of data duplication or errors, they are employed to guarantee that each data entry or identifier is distinct and unique. 
  • To enforce uniqueness constraints and uphold data integrity, database management systems frequently use unique numbers. 
  • They aid in the detection and correction of data inconsistencies, the prevention of data corruption, and the improvement of data quality.

B. Cryptography and Security Systems

  • The use of unique numbers is widespread in cryptography and security protocols. 
  • In encryption algorithms, secure communication protocols, and authentication mechanisms, they act as keys, identifiers, or random values. 
  • The generation of secure cryptographic keys using distinctive numbers helps to protect the confidentiality, integrity, and authenticity of sensitive data. 
  • They are used to strengthen the general security of systems and data through secure protocols like digital signatures, key exchange, and secure hashing algorithms.

C. Mathematical Puzzles and Games

  • In mathematical games and puzzles, unique numbers play a fascinating role. 
  • Puzzle exercises often incorporate the frequent usage of numbers to uncover or generate numbers with specific special qualities or traits. 
  • Recreational mathematics, mathematical competitions, and brain teasers involve the exploration of distinct number patterns and properties. 
  • The idea of uniqueness is essential to games like Sudoku, where distinct numbers must appear in every row, column, and subgrid. 
  • The use of unique numbers enhances the interest, challenge, and thought-provoking nature of various mathematical games and puzzles.

Unique numbers are essential in many fields, enhancing efficiency, accuracy, and security through data validation and security to entertaining puzzles and games.

We hope our blog on “Unique number in Java” was helpful in your journey of mastering Java Programming language. For more informative blogs about Java and other programming languages keep checking on our official website Newtum. Keep learning and coding!

About The Author

Leave a Reply