Count of digits in N and M that are same and are present on the same indices
Last Updated :
12 Dec, 2022
Given two number N and M, the task is to find the count of digits in N and M that are the same and are present on the same indices.
Examples:
Input: N = 123, M = 321
Output: 1
Explanation: Digit 2 satisfies the condition
Input: N = 123, M = 111
Output: 1
Approach: The problem can be solved using two-pointer approach.
- Convert N and M for ease of traversal
- Create two pointers where one pointer points to the first digit of N and the other to the first digit of M respectively initially.
- Now traverse both the numbers left to right and check if the digits on both pointers are same or not.
- If yes, increase the count.
- Increase the pointer by 1 on each iteration.
- Return the final count at the end.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int countDigits( int N, int M)
{
string a = to_string(N), b = to_string(M);
int same_dig_cnt = 0;
for ( int i = 0; i < a.length() && b.length(); i++)
if (a[i] == b[i])
same_dig_cnt++;
return same_dig_cnt;
}
int main()
{
int N = 123, M = 321;
cout << countDigits(N, M);
return 0;
}
|
Java
import java.io.*;
public class GFG {
static int countDigits( int N, int M) {
String a = Integer.toString(N), b = Integer.toString(M);
int same_dig_cnt = 0 ;
for ( int i = 0 ; i < a.length() && i < b.length(); i++)
if (a.charAt(i) == b.charAt(i))
same_dig_cnt++;
return same_dig_cnt;
}
public static void main(String args[])
{
int N = 123 , M = 321 ;
System.out.println(countDigits(N, M));
}
}
|
Python3
def countDigits(N, M):
a = str (N)
b = str (M)
same_dig_cnt = 0 ;
i = 0
while (i < len (a) and len (b)):
if (a[i] = = b[i]):
same_dig_cnt + = 1
i + = 1
return same_dig_cnt;
N = 123
M = 321 ;
print (countDigits(N, M));
|
C#
using System;
using System.Collections;
class GFG
{
static int countDigits( int N, int M)
{
string a = N.ToString(), b = M.ToString();
int same_dig_cnt = 0;
for ( int i = 0; i < a.Length && i < b.Length; i++)
if (a[i] == b[i])
same_dig_cnt++;
return same_dig_cnt;
}
public static void Main()
{
int N = 123, M = 321;
Console.Write(countDigits(N, M));
}
}
|
Javascript
<script>
function countDigits(N, M) {
let a = (N).toString(), b = (M).toString();
let same_dig_cnt = 0;
for (let i = 0; i < a.length && b.length; i++)
if (a[i] == b[i])
same_dig_cnt++;
return same_dig_cnt;
}
let N = 123, M = 321;
document.write(countDigits(N, M));
</script>
|
Time Complexity: O(D), where D is the min count of digits in N or M
Auxiliary Space: O(D), where D is the max count of digits in N or M
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...