N 和 M 中相同且出现在相同索引上的数字计数
给定两个数字N和M ,任务是找到N和M中相同且出现在相同索引上的数字的计数。
例子:
Input: N = 123, M = 321
Output: 1
Explanation: Digit 2 satisfies the condition
Input: N = 123, M = 111
Output: 1
方法:可以使用两指针方法解决问题。
- 转换 N 和 M 以便于遍历
- 创建两个指针,其中一个指针最初指向 N 的第一个数字,另一个指向 M 的第一个数字。
- 现在从左到右遍历两个数字并检查两个指针上的数字是否相同。
- 如果是,请增加计数。
- 每次迭代将指针加 1。
- 最后返回最终计数。
下面是上述方法的实现:
C++
// C++ implementation of the above approach
#include
using namespace std;
int countDigits(int N, int M)
{
// Convert N and M to string
// for ease of traversal
string a = to_string(N), b = to_string(M);
int same_dig_cnt = 0;
// Find the count of digits
// that are same and occur on same indices
// in both N and M.
// Store the count in variable same_dig_cnt
for (int i = 0; i < a.length() && b.length(); i++)
if (a[i] == b[i])
same_dig_cnt++;
return same_dig_cnt;
}
// Driver code
int main()
{
int N = 123, M = 321;
cout << countDigits(N, M);
return 0;
Java
// Java implementation of the above approach
class GFG {
static int countDigits(int N, int M) {
// Convert N and M to string
// for ease of traversal
String a = Integer.toString(N), b = Integer.toString(M);
int same_dig_cnt = 0;
// Find the count of digits
// that are same and occur on same indices
// in both N and M.
// Store the count in variable same_dig_cnt
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;
}
// Driver code
public static void main(String args[])
{
int N = 123, M = 321;
System.out.println(countDigits(N, M));
}
}
// This code is contributed by gfgking
Python3
# Python code for the above approach
def countDigits(N, M):
# Convert N and M to string
# for ease of traversal
a = str(N)
b = str(M)
same_dig_cnt = 0;
# Find the count of digits
# that are same and occur on same indices
# in both N and M.
# Store the count in variable same_dig_cnt
i = 0
while(i < len(a) and len(b)):
if (a[i] == b[i]):
same_dig_cnt += 1
i += 1
return same_dig_cnt;
# Driver code
N = 123
M = 321;
print(countDigits(N, M));
# This code is contributed by Saurabh Jaiswal
C#
// C# implementation of the above approach
using System;
using System.Collections;
class GFG
{
static int countDigits(int N, int M)
{
// Convert N and M to string
// for ease of traversal
string a = N.ToString(), b = M.ToString();
int same_dig_cnt = 0;
// Find the count of digits
// that are same and occur on same indices
// in both N and M.
// Store the count in variable same_dig_cnt
for (int i = 0; i < a.Length && i < b.Length; i++)
if (a[i] == b[i])
same_dig_cnt++;
return same_dig_cnt;
}
// Driver code
public static void Main()
{
int N = 123, M = 321;
Console.Write(countDigits(N, M));
}
}
// This code is contributed by Samim Hossain Mondal.
Javascript
输出
1
时间复杂度: O(D),其中 D 是 N 或 M 中的最小位数
辅助空间: O(D),其中 D 是 N 或 M 中的最大位数