Count of integers in an Array whose length is a multiple of K
Last Updated :
05 Jan, 2023
Given an array arr of N elements and an integer K, the task is to count all the elements whose length is a multiple of K.
Examples:
Input: arr[]={1, 12, 3444, 544, 9}, K = 2
Output: 2
Explanation:
There are 2 numbers whose digit count is multiple of 2 {12, 3444}.
Input: arr[]={12, 345, 2, 68, 7896}, K = 3
Output: 1
Explanation:
There is 1 number whose digit count is multiple of 3 {345}.
Approach:
- Traverse the numbers in the array one by one
- Count the digits of every number in the array
- Check if its digit count is a multiple of K or not.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int digit_count( int x)
{
int sum = 0;
while (x) {
sum++;
x = x / 10;
}
return sum;
}
int find_count(vector< int > arr, int k)
{
int ans = 0;
for ( int i : arr) {
int x = digit_count(i);
if (x % k == 0)
ans += 1;
}
return ans;
}
int main()
{
vector< int > arr
= { 12, 345, 2, 68, 7896 };
int K = 2;
cout << find_count(arr, K);
return 0;
}
|
Java
class GFG{
static int digit_count( int x)
{
int sum = 0 ;
while (x > 0 ) {
sum++;
x = x / 10 ;
}
return sum;
}
static int find_count( int []arr, int k)
{
int ans = 0 ;
for ( int i : arr) {
int x = digit_count(i);
if (x % k == 0 )
ans += 1 ;
}
return ans;
}
public static void main(String[] args)
{
int []arr = { 12 , 345 , 2 , 68 , 7896 };
int K = 2 ;
System.out.print(find_count(arr, K));
}
}
|
Python3
def digit_count(x):
sum = 0
while (x):
sum + = 1
x = x / / 10
return sum
def find_count(arr,k):
ans = 0
for i in arr:
x = digit_count(i)
if (x % k = = 0 ):
ans + = 1
return ans
if __name__ = = '__main__' :
arr = [ 12 , 345 , 2 , 68 , 7896 ]
K = 2
print (find_count(arr, K))
|
C#
using System;
public class GFG{
static int digit_count( int x)
{
int sum = 0;
while (x > 0) {
sum++;
x = x / 10;
}
return sum;
}
static int find_count( int []arr, int k)
{
int ans = 0;
foreach ( int i in arr) {
int x = digit_count(i);
if (x % k == 0)
ans += 1;
}
return ans;
}
public static void Main(String[] args)
{
int []arr = { 12, 345, 2, 68, 7896 };
int K = 2;
Console.Write(find_count(arr, K));
}
}
|
Javascript
<script>
function digit_count(x)
{
let sum = 0;
while (x) {
sum++;
x = x / 10;
}
return sum;
}
function find_count(arr, k)
{
let ans = 0;
for (let i of arr) {
let x = digit_count(i);
if (x % k == 0)
ans += 1;
}
return ans;
}
let arr = [ 12, 345, 2, 68, 7896 ];
let K = 2;
document.write(find_count(arr, K));
</script>
|
Time complexity:- O(N*log10M), where N is the size of array, and M is the largest number in the array.
Space complexity:- O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...