Count digits present in each element of a given Matrix
Last Updated :
07 Mar, 2022
Given a matrix arr[][] of dimensions M * N, the task is to count the number of digits of every element present in the given matrix.
Examples:
Input: arr[][] = { { 27, 173, 5 }, { 21, 6, 624 }, { 5, 321, 49 } }
Output:
2 3 1
2 1 3
1 3 2
Input: arr[][] = { {11, 12, 33 }, { 64, 57, 61 }, { 74, 88, 39 } }
Output:
2 2 2
2 2 2
2 2 2
Approach: The idea to solve this problem is to traverse the given matrix and for every index of the matrix, count the number of digits of the number present at that index using the following expression:
Number of digits present in any value X is given by floor(log10(X))+1.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
const int M = 3;
const int N = 3;
void countDigit( int arr[M][N])
{
for ( int i = 0; i < M; i++) {
for ( int j = 0; j < N; j++) {
int X = arr[i][j];
int d = floor ( log10 (X) * 1.0) + 1;
cout << d << " " ;
}
cout << endl;
}
}
int main()
{
int arr[][3] = { { 27, 173, 5 },
{ 21, 6, 624 },
{ 5, 321, 49 } };
countDigit(arr);
return 0;
}
|
Java
import java.util.*;
class GFG
{
static int M = 3 ;
static int N = 3 ;
static void countDigit( int arr[][])
{
for ( int i = 0 ; i < M; i++)
{
for ( int j = 0 ; j < N; j++)
{
int X = arr[i][j];
int d = ( int ) (Math.floor(Math.log10(X) * 1.0 ) + 1 );
System.out.print(d+ " " );
}
System.out.println();
}
}
public static void main(String[] args)
{
int arr[][] = { { 27 , 173 , 5 },
{ 21 , 6 , 624 },
{ 5 , 321 , 49 } };
countDigit(arr);
}
}
|
Python3
from math import floor, log10
M = 3
N = 3
def countDigit(arr):
for i in range (M):
for j in range (N):
X = arr[i][j]
d = floor(log10(X) * 1.0 ) + 1
print (d, end = " " )
print ()
if __name__ = = '__main__' :
arr = [ [ 27 , 173 , 5 ],
[ 21 , 6 , 624 ],
[ 5 , 321 , 49 ] ]
countDigit(arr)
|
C#
using System;
class GFG
{
static int M = 3;
static int N = 3;
static void countDigit( int [,] arr)
{
for ( int i = 0; i < M; i++)
{
for ( int j = 0; j < N; j++)
{
int X = arr[i, j];
int d = ( int ) (Math.Floor(Math.Log10(X) * 1.0) + 1);
Console.Write(d + " " );
}
Console.WriteLine();
}
}
public static void Main()
{
int [,] arr = { { 27, 173, 5 },
{ 21, 6, 624 },
{ 5, 321, 49 } };
countDigit(arr);
}
}
|
Javascript
<script>
let M = 3;
let N = 3;
function countDigit(arr)
{
for (let i = 0; i < M; i++)
{
for (let j = 0; j < N; j++)
{
let X = arr[i][j];
let d = (Math.floor(Math.log10(X) * 1.0) + 1);
document.write(d+ " " );
}
document.write( "<br/>" );
}
}
let arr = [[ 27, 173, 5 ],
[ 21, 6, 624 ],
[ 5, 321, 49 ]];
countDigit(arr);
</script>
|
Output:
2 3 1
2 1 3
1 3 2
Time Complexity: O(M * N)
Auxiliary Space: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...