A unique number is a number in which no digit is repeated. For example: 102452 is not a unique number as 2 is repeated twice while 2374 is a unique number. So in this article I am sharing the C++ program that check if a number is unique or not.
Also Read: C++ Program to check whether a number is prime number or not
Also Read: C++ Program check whether a number is palindrome or not
Also Read: C++ Program check whether a number is palindrome or not
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 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 |
#include<iostream> #include<stdlib.h> using namespace std; int main() { long num; char str[10]; int a[10]={0},flag=1,i=0; cout<<"Enter any number:"; cin>>num; itoa(num,str,10); //convert number to character array while(str[i]!='\0') { switch(str[i]) { case '0': a[0]++; break; case '1': a[1]++; break; case '2': a[2]++; break; case '3': a[3]++; break; case '4': a[4]++; break; case '5': a[5]++; break; case '6': a[6]++; break; case '7': a[7]++; break; case '8': a[8]++; break; case '9': a[9]++; break; } i++; } for(i=0;i<10;i++) { if(a[i]>1) { flag=0; break; } } if(flag) cout<<"\nNumber is Unique"; else cout<<"\nNumber is Not Unique"; return 0; } |
Output
You could just sort this string, and check with one for(). Like this:
#include
#include
#include
int main() {
char num[100];
scanf("%s", num); // read number as string
int len = strlen(num);
std::sort(num, num+len); // sort string
for (int i = 1; i < len; i++) {
if (num[i-1] == num[i]) {
printf("nNumber is Not Unique");
return 0;
}
}
printf("nNumber is Unique");
return 0;
}
Thanks for sharing another solution with us.
I just did it. Hope you like it 🙂
bool is_unique_number(char * snumber) {
for (int j = 0; j <= 9; j++) {
int counter = 0;
for (int i = 0; snumber[i] != ''; i++)
if ((snumber[i] – '0') == j)
counter++;
if (counter > 1)
return false;
}
return true;
}
Please start a YouTube channel for breif knowledge…. Some of the starting programmers like me had to face a lot of difficulty in understanding!