Check if given number contains a digit which is the average of all other digits
Last Updated :
07 Oct, 2022
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 digits.
Approach:
To solve the problem, follow the steps below:
- Store the sum and count of digits of N.
- Store the digits in a Set .
- If sum%count is 0 and the integer sum/count is present in the Set, that is sum/count is a digit of N, then print Yes. Otherwise print No.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void check( int n)
{
set< int > digits;
int temp = n;
int sum = 0;
int count = 0;
while (temp > 0) {
sum += temp % 10;
digits.insert(temp % 10);
count++;
temp = temp / 10;
}
if (sum % count == 0
&& digits.find(sum / count)
!= digits.end())
cout << "Yes" << endl;
else
cout << "No" << endl;
}
int main()
{
int n = 42644;
check(n);
}
|
Java
import java.util.*;
class GFG{
static void check( int n)
{
HashSet<Integer> digits = new HashSet<Integer>();
int temp = n;
int sum = 0 ;
int count = 0 ;
while (temp > 0 )
{
sum += temp % 10 ;
digits.add(temp % 10 );
count++;
temp = temp / 10 ;
}
if (sum % count == 0 &&
digits.contains(sum / count))
System.out.print( "Yes" + "\n" );
else
System.out.print( "No" + "\n" );
}
public static void main(String[] args)
{
int n = 42644 ;
check(n);
}
}
|
Python3
def check (n):
digits = set ()
temp = n
Sum = 0
count = 0
while (temp > 0 ):
Sum + = temp % 10
digits.add(temp % 10 )
count + = 1
temp = temp / / 10
if (( Sum % count = = 0 ) and
(( int )( Sum / count) in digits)):
print ( "Yes" )
else :
print ( "No" )
n = 42644
check(n)
|
C#
using System;
using System.Collections.Generic;
class GFG{
static void check( int n)
{
HashSet< int > digits = new HashSet< int >();
int temp = n;
int sum = 0;
int count = 0;
while (temp > 0)
{
sum += temp % 10;
digits.Add(temp % 10);
count++;
temp = temp / 10;
}
if (sum % count == 0 &&
digits.Contains(sum / count))
Console.Write( "Yes" + "\n" );
else
Console.Write( "No" + "\n" );
}
public static void Main(String[] args)
{
int n = 42644;
check(n);
}
}
|
Javascript
<script>
function check(n)
{
var digits = new Set();
var temp = n;
var sum = 0;
var count = 0;
while (temp > 0) {
sum += temp % 10;
digits.add(temp % 10);
count++;
temp = parseInt(temp / 10);
}
if (sum % count == 0
&& digits.has(sum / count))
document.write( "Yes" );
else
document.write( "No" );
}
var n = 42644;
check(n);
</script>
|
Time Complexity: O(log10N)
Auxiliary Space: O(1) because constant space for the set is required.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...