In this tutorial you will learn about the Program to check Unique Number In Java and its application with practical example.
In this tutorial, we will learn to create a Program to check Unique Number in Java using Java programming.
Prerequisites
Before starting with this tutorial we assume that you are best aware of the following Java programming topics:
- Java Operators.
- Basic Input and Output function in Java.
- Class and Object in Java.
- Basic Java programming.
- If-else statements in Java.
- For loop in Java.
What is Unique Number.
The number is called a unique if there is no repeated digits in the given number.
For Example:=> 20, 56, 98 are Unique Number
But => “22,99,121,100” are not unique because they contain repeated digits in them.
Program to check Unique Number In Java
In this program we would find the given number is a Unique number or not .first of all we would take a value from user and find the Unique number.let have a look at the code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
// java program to find unique number.. import java.util.Scanner; public class Unique_Num { public static void main(String args[]) { //Decalring variabels int rem, rem1, number, num1, num2, count = 0; Scanner sc = new Scanner(System.in); System.out.print("Enter any number "); number = sc.nextInt(); //num1 and num2 are temporary variable num1 = number; num2 = number; //iterate over all digits of the number while (num1 > 0) { //detrmins the last digit of the number rem = num1 % 10; while (num2 > 0) { //finds the last digit rem1 = num2 % 10; //comparing the last digit if (rem == rem1) { //increments the count variable by 1 count++; } //removes the last digit from the number num2 = num2 / 10; } //removes the last digit from the number num1 = num1 / 10; } if (count == 1) { System.out.println("The number is unique."); } else { System.out.println("The number is not unique."); } } } |
Output
Unique Number
Not a Unique Number.
In the above program, we have first declared and initialized a set variables required in the program.
- number= it will hold entered number.
- num1,num2=it will hold temporary number.
- count= it will hold repetition number,
- rem,rem1- it will hold last digit of a numbers.
After that we take a number from user and find given number is a Unique number or not.
Steps to check given number is unique or not:
- take a value from the user in number variable.
- Break digit and find the last digit o the number.
- Check each digit in number with the last digit.
- If the digit repeated more than one time, the number is not unique.
- Else, remove the last digit of the number.
- Repeat steps until the number becomes zero.
The number is called a unique if there is no repeated digits in the given number.
else it is not a unique number.