Program to check if a given number is Lucky (all digits are different)
Last Updated :
12 Apr, 2023
A number is lucky if all digits of the number are different. How to check if a given number is lucky or not.
Examples:
Input: n = 983
Output: true
All digits are different
Input: n = 9838
Output: false
8 appears twice
We strongly recommend you to minimize your browser and try this yourself first.
The idea is to traverse through every digit of given number and mark the traversed digit as visited. Since the total number of digits is 10, we need a boolean array of size only 10 to mark visited digits.
Below is the implementation of above idea.
C++
// C++ program to check if a given number is lucky
#include<iostream>
using namespace std;
// This function returns true if n is lucky
bool isLucky(int n)
{
// Create an array of size 10 and initialize all
// elements as false. This array is used to check
// if a digit is already seen or not.
bool arr[10];
for (int i=0; i<10; i++)
arr[i] = false;
// Traverse through all digits of given number
while (n > 0)
{
// Find the last digit
int digit = n%10;
// If digit is already seen, return false
if (arr[digit])
return false;
// Mark this digit as seen
arr[digit] = true;
// REmove the last digit from number
n = n/10;
}
return true;
}
// Driver program to test above function.
int main()
{
int arr[] = {1291, 897, 4566, 1232, 80, 700};
int n = sizeof(arr)/sizeof(arr[0]);
for (int i=0; i<n; i++)
isLucky(arr[i])? cout << arr[i] << " is Lucky \n":
cout << arr[i] << " is not Lucky \n";
return 0;
}
Java
// Java program to check if
// a given number is lucky
class GFG
{
// This function returns true if n is lucky
static boolean isLucky(int n)
{
// Create an array of size 10 and initialize all
// elements as false. This array is used to check
// if a digit is already seen or not.
boolean arr[]=new boolean[10];
for (int i = 0; i < 10; i++)
arr[i] = false;
// Traverse through all digits
// of given number
while (n > 0)
{
// Find the last digit
int digit = n % 10;
// If digit is already seen,
// return false
if (arr[digit])
return false;
// Mark this digit as seen
arr[digit] = true;
// Remove the last digit from number
n = n / 10;
}
return true;
}
// Driver code
public static void main (String[] args)
{
int arr[] = {1291, 897, 4566, 1232, 80, 700};
int n = arr.length;
for (int i = 0; i < n; i++)
if(isLucky(arr[i]))
System.out.print(arr[i] + " is Lucky \n");
else
System.out.print(arr[i] + " is not Lucky \n");
}
}
// This code is contributed by Anant Agarwal.
Python3
# python program to check if a
# given number is lucky
import math
# This function returns true
# if n is lucky
def isLucky(n):
# Create an array of size 10
# and initialize all elements
# as false. This array is
# used to check if a digit
# is already seen or not.
ar = [0] * 10
# Traverse through all digits
# of given number
while (n > 0):
#Find the last digit
digit = math.floor(n % 10)
# If digit is already seen,
# return false
if (ar[digit]):
return 0
# Mark this digit as seen
ar[digit] = 1
# REmove the last digit
# from number
n = n / 10
return 1
# Driver program to test above function.
arr = [1291, 897, 4566, 1232, 80, 700]
n = len(arr)
for i in range(0, n):
k = arr[i]
if(isLucky(k)):
print(k, " is Lucky ")
else:
print(k, " is not Lucky ")
# This code is contributed by Sam007.
C#
// C# program to check if
// a given number is lucky
using System;
class GFG {
// This function returns true if
// n is lucky
static bool isLucky(int n)
{
// Create an array of size 10
// and initialize all elements
// as false. This array is used
// to check if a digit is
// already seen or not.
bool []arr = new bool[10];
for (int i = 0; i < 10; i++)
arr[i] = false;
// Traverse through all digits
// of given number
while (n > 0)
{
// Find the last digit
int digit = n % 10;
// If digit is already seen,
// return false
if (arr[digit])
return false;
// Mark this digit as seen
arr[digit] = true;
// Remove the last digit
// from number
n = n / 10;
}
return true;
}
// Driver code
public static void Main ()
{
int []arr = {1291, 897, 4566, 1232,
80, 700};
int n = arr.Length;
for (int i = 0; i < n; i++)
if(isLucky(arr[i]))
Console.Write(arr[i] +
" is Lucky \n");
else
Console.Write(arr[i] +
" is not Lucky \n");
}
}
// This code is contributed by sam007.
PHP
<?php
// PHP program to check if a given
// number is lucky
// This function returns true
// if n is lucky
function isLucky($n)
{
// Create an array of size 10 and
// initialize all elements as false.
// This array is used to check if a
// digit is already seen or not.
$arr = array();
for ($i = 0; $i < 10; $i++)
$arr[$i] = false;
// Traverse through all digits
// of given number
while ($n > 0)
{
// Find the last digit
$digit = $n % 10;
// If digit is already seen,
// return false
if ($arr[$digit])
return false;
// Mark this digit as seen
$arr[$digit] = true;
// Remove the last digit
// from number
$n = (int)($n / 10);
}
return true;
}
// Driver Code
$arr = array(1291, 897, 4566,
1232, 80, 700);
$n = sizeof($arr);
for ($i = 0; $i < $n; $i++)
if(isLucky($arr[$i]))
echo $arr[$i] , " is Lucky \n";
else
echo $arr[$i] , " is not Lucky \n";
// This code is contributed by jit_t
?>
JavaScript
<script>
// Javascript program to check if a given number is lucky
// This function returns true if n is lucky
function isLucky(n)
{
// Create an array of size 10 and initialize all
// elements as false. This array is used to check
// if a digit is already seen or not.
var arr=Array(10).fill(0);
for (var i=0; i<10; i++)
arr[i] = false;
// Traverse through all digits of given number
while (n > 0)
{
// Find the last digit
var digit = n%10;
// If digit is already seen, return false
if (arr[digit])
return false;
// Mark this digit as seen
arr[digit] = true;
// REmove the last digit from number
n = parseInt(n/10);
}
return true;
}
// Driver program to test above function.
var arr = [1291, 897, 4566, 1232, 80, 700]
var n = arr.length;
for (var i=0; i<n; i++)
isLucky(arr[i])? document.write( arr[i] + " is Lucky<br>"):
document.write(arr[i] + " is not Lucky<br>");
</script>
Output:
1291 is not Lucky
897 is Lucky
4566 is not Lucky
1232 is not Lucky
80 is Lucky
700 is not Lucky
Time Complexity: O(d) where d is a number of digits in the input number.
Auxiliary Space: O(1)
Method 2:(using STL and sorting)
In this method we will firstly convert the number into a string. Then we will sort the whole string. Then we will compare every index element with the next index element. If both are equal then we will stop that position and will print that the given number is not lucky.
And if we do not get any index as discussed above then we will print that given number is lucky.
This whole task will be completed in O(K) time where K is the total number of digits of N.
Below is the implementation of the above approach:
C++
// C++ code to check is the number
// lucky or not.
#include <bits/stdc++.h>
using namespace std;
void checklucky(string s,int n)
{
bool x = false;
// traversing the whole string
for (int i = 0; i < s.length() - 1; i++)
{
// checking next element whether
// it is equal or not
if (s[i] == s[i + 1])
{
cout << n << " is not lucky number"<<endl;
x = true;
break;
}
}
if (!x)
{
cout << n << " is lucky number"<<endl;
}
}
int main()
{
int n1 = 1234,n2=5868;
// converting the number from
// integer to string using
// C++ STL function.
string s1 = to_string(n1);
string s2 = to_string(n2);
// sorting the string
sort(s1.begin(), s1.end());
sort(s2.begin(), s2.end());
//function calling
checklucky(s1,n1);
checklucky(s2,n2);
return 0;
}
//this code is contributed by Machhaliya Muhammad
Java
// Java code to check is the number
// lucky or not.
import java.util.*;
class GFG {
static void checklucky(char[] s, int n)
{
boolean x = false;
// traversing the whole string
for (int i = 0; i < s.length - 1; i++)
{
// checking next element whether
// it is equal or not
if (s[i] == s[i + 1]) {
System.out.println(
n + " is not lucky number");
x = true;
break;
}
}
if (!x) {
System.out.println(n + " is lucky number");
}
}
public static void main(String[] args)
{
int n1 = 1234, n2 = 5868;
// converting the number from
// integer to string using
// library function.
char[] s1 = String.valueOf(n1).toCharArray();
char[] s2 = String.valueOf(n2).toCharArray();
// sorting the string
Arrays.sort(s1);
Arrays.sort(s2);
// function calling
checklucky(s1, n1);
checklucky(s2, n2);
}
}
// this code is contributed by phasing17
Python3
# Python3 code to check is the number
# lucky or not.
def checklucky(s, n):
x = False
# traversing the whole string
for i in range(len(s) - 1):
# checking next element whether
# it is equal or not
if (s[i] == s[i + 1]):
print(n, "is not a lucky number")
return
if not x:
print(n, "is a lucky number")
# Driver Code
n1 = 1234
n2 = 5868
# converting the number from
# integer to string
s1 = str(n1)
s2 = str(n2)
# sorting the string
s1 = "".join(sorted(s1))
s2 = "".join(sorted(s2))
# function calling
checklucky(s1, n1)
checklucky(s2, n2)
# this code is contributed by phasing17
C#
// C# code to check is the number
// lucky or not.
using System;
using System.Collections.Generic;
class GFG {
static void checklucky(char[] s, int n)
{
bool x = false;
// traversing the whole string
for (int i = 0; i < s.Length - 1; i++) {
// checking next element whether
// it is equal or not
if (s[i] == s[i + 1]) {
Console.WriteLine(n
+ " is not lucky number");
x = true;
break;
}
}
if (!x) {
Console.WriteLine(n + " is lucky number");
}
}
public static void Main(string[] args)
{
int n1 = 1234, n2 = 5868;
// converting the number from
// integer to string using
// library function.
char[] s1 = Convert.ToString(n1).ToCharArray();
char[] s2 = Convert.ToString(n2).ToCharArray();
// sorting the string
Array.Sort(s1);
Array.Sort(s2);
// function calling
checklucky(s1, n1);
checklucky(s2, n2);
}
}
// this code is contributed by phasing17
JavaScript
// JavaScript code to check is the number
// lucky or not.
function checklucky(s, n)
{
let x = false;
// traversing the whole string
for (var i = 0; i < s.length - 1; i++)
{
// checking next element whether
// it is equal or not
if (s[i] == s[i + 1])
{
console.log(n + " is not lucky number");
x = true;
break;
}
}
if (!x)
{
console.log(n + " is lucky number");
}
}
let n1 = 1234,n2=5868;
// converting the number from
// integer to string
let s1 = n1.toString();
let s2 = n2.toString();
// sorting the string
s1 = s1.split("");
s2 = s2.split("");
s1.sort();
s2.sort();
s1 = s1.join("");
s2 = s2.join("");
// function calling
checklucky(s1,n1);
checklucky(s2,n2);
// this code is contributed by phasing17
Output1234 is lucky number
5868 is not lucky number
Time Complexity: O(n1*logn1 + n2*logn2), where n1 and n2 represents the lengths of the given strings.
Auxiliary Space: O(1), no extra space is required, so it is a constant.
Method 3:(Using set)
In this method we will store all digits in set and check if size of set is equal to no. of digits in number. If equal then it is lucky number otherwise it is not a lucky number.
C++
#include <iostream>
#include <set>
using namespace std;
bool check(int n)
{
set<int> s;
int sz = 0;
while (n > 0) {
int rem = n % 10;
sz++;
s.insert(rem);
n /= 10;
}
return (s.size() == sz);
}
int main()
{
int n = 9876;
if (check(n)) {
cout << n << " is a lucky number." << endl;
}
else {
cout << n << " is not a lucky number." << endl;
}
return 0;
}
Java
import java.util.HashSet;
import java.util.Set;
public class Main {
public static boolean check(int n) {
Set<Integer> s = new HashSet<Integer>();
int sz = 0;
while (n > 0) {
int rem = n % 10;
sz++;
s.add(rem);
n /= 10;
}
return (s.size() == sz);
}
public static void main(String[] args) {
int n = 9876;
if (check(n)) {
System.out.println(n + " is a lucky number.");
} else {
System.out.println(n + " is not a lucky number.");
}
}
}
Python3
def check(n: int) -> bool:
s = set()
sz = 0
while n > 0:
rem = n % 10
sz += 1
s.add(rem)
n //= 10
return (len(s) == sz)
n = 9876
if check(n):
print(f"{n} is a lucky number.")
else:
print(f"{n} is not a lucky number.")
C#
using System;
using System.Collections.Generic;
class GFG {
// This function checks whether n is a lucky number
static bool Check(int n)
{
// Set to store digits
HashSet<int> s = new HashSet<int>();
int sz = 0;
// Extracting all the digits
while (n > 0) {
int rem = n % 10;
sz++;
s.Add(rem);
n /= 10;
}
return (s.Count == sz);
}
// Driver code
static void Main(string[] args)
{
int n = 9876;
// Function call
if (Check(n)) {
Console.WriteLine(n + " is a lucky number.");
}
else {
Console.WriteLine(n + " is not a lucky number.");
}
}
}
// This code is contributed by phasing17.
JavaScript
// JS code to implement the approach
// Function to check if a number is a lucky number
function check(n)
{
// Initialize an empty set and size variable
let s = new Set();
let sz = 0;
// While n is greater than 0
while (n > 0) {
// Get the remainder when n is divided by 10
let rem = n % 10;
sz += 1;
s.add(rem);
// Divide n by 10 and floor the result
n = Math.floor(n / 10);
}
// Return true if the size of the set is equal to sz,
// else return false
return (s.size == sz);
}
let n = 9876;
// Check if n is a lucky number
if (check(n)) {
console.log(`${ n } is a lucky number.`);
}
else {
console.log(`${ n } is not a lucky number.`);
}
// This code is contributed by phasing17
Output9876 is a lucky number.
Time complexity : O(log(n))
Space Complexity : O(log(n)) because the set is storing log(n) elements
Similar Reads
Program to check if a number is divisible by any of its digits
Given an integer N where 1 \leq n \leq 10^{18} . The task is to check whether the number is not divisible by any of its digit. If the given number N is divisible by any of its digits then print "YES" else print "NO". Examples: Input : N = 5115Output : YESExplanation: 5115 is divisible by both 1 and
10 min read
Check if all the digits of the given number are same
Given a positive integer N, the task is to check whether all the digits of the given integer N are the same or not. If found to be true, then print Yes. Otherwise, print No. Examples: Input: N = 222Output: Yes Input: N = 232Output: No Recommended: Please try your approach on {IDE} first, before movi
11 min read
Check if given number contains a digit which is the average of all other digits
Given an integer N, the task is to check whether N contains a digit D such that it is the average of all other digits present in N. Examples: Input: N = 132 Output: Yes Explanation: Since, (1 + 3)/2 = 2. Input: N = 436 Output: No Explanation: No such digit exists which is the average of all other di
5 min read
Program to check if a number is divisible by sum of its digits
Given an integer N, the task is to check whether the number is divisible by the sum of its digits or not. If divisible, then print âYESâ else print âNOâ. Examples: Input: N = 12 Output: YES Explanation: As sum of digits of 12 = 1 + 2 = 3 and 12 is divisible by 3 So the output is YES Input: N = 123 O
7 min read
Check if all digits of a number divide it
Given a number n, find whether all digits of n divide it or not.Examples: Input : 128 Output : Yes 128 % 1 == 0, 128 % 2 == 0, and 128 % 8 == 0. Input : 130 Output : No We want to test whether each digit is non-zero and divides the number. For example, with 128, we want to test d != 0 && 128
9 min read
Check if the sum of digits of number is divisible by all of its digits
Given an integer N, the task is to check whether the sum of digits of the given number is divisible by all of its digits or not. If divisible then print Yes else print No. Examples: Input: N = 12 Output: No Sum of digits = 1 + 2 = 3 3 is divisible by 1 but not 2. Input: N = 123 Output: Yes Approach:
14 min read
Check if the frequency of all the digits in a number is same
Given a positive number 'N', the task is to find whether 'N' is balanced or not. Output 'YES' if 'N' is a balanced number else 'NO'. A number is balanced if the frequency of all the digits in it is same i.e. all the digits appear the same number of times. Examples: Input: N = 1234567890 Output: YES
8 min read
Count of numbers with all digits same in a given range
Given two integers L and R denoting the starting and end values of a range, the task is to count all numbers in that range whose all digit are same, like 1, 22, 444, 3333, etc.Example: Input: L = 12, R = 68 Output: 5 Explanation: { 22, 33, 44, 55, 66} are the numbers with same digits in the given ra
9 min read
Given a large number, check if a subsequence of digits is divisible by 8
Given a number of at most 100 digits. We have to check if it is possible, after removing certain digits, to obtain a number of at least one digit which is divisible by 8. We are forbidden to rearrange the digits. Examples : Input : 1787075866 Output : Yes There exist more one or more subsequences di
15+ min read
Check if a N base number is Even or Odd
Given a number num in base N, check whether it is even or odd.Examples: Input: num = 10, N = 8 Output: Even Explanation: 108 = 810, which is even Input: num = 122, N = 5 Output: Odd Explanation: 1225 = 3710, which is odd Approach: Convert the number num from Base N to Decimal base.Check whether the
6 min read