Common Digits in Two Numbers

The program must accept two integers A and B as the input. The task is to print all the unique digits that are present in both numbers. The digits must be printed in ascending order. If no digits are common, print -1.

Boundary Condition(s):
1 <= A, B <= 10^9

Input Format:
The first line contains the number A.
The second line contains the number B.

Output Format:
The first line contains the common digits in ascending order or -1.

Example Input/Output 1:
Input:
123
456

Output:
-1

Explanation:
There are no common digits between 123 and 456.

Example Input/Output 2:
Input:
1289
45912

Output:
12

Explanation:
The common digits between 1289 and 45912 are 1 and 2.

a, b = set(input().strip()), set(input().strip())
common_digits = sorted(a.intersection(b))
if common_digits:
    print("".join(common_digits))
else:
    print(-1)
#include<stdio.h>

int main() {
    char a[12], b[12];
    scanf("%s", a);
    scanf("%s", b);
    int common[10] = {0}, found = 0;
    for(int i = 0; a[i]; i++)
        for(int j = 0; b[j]; j++)
            if(a[i] == b[j])
                common[a[i] - '0'] = 1;
    for(int i = 0; i < 10; i++) {
        if(common[i]) {
            printf("%d", i);
            found = 1;
        }
    }
    if(!found) printf("-1");
    return 0;
}
#include <iostream>
#include <string>
using namespace std;

int main() {
    string a, b;
    cin >> a >> b;
    bool common[10] = {false}, found = false;
    for(char c1 : a)
        for(char c2 : b)
            if(c1 == c2)
                common[c1 - '0'] = true;
    for(int i = 0; i < 10; i++) {
        if(common[i]) {
            cout << i;
            found = true;
        }
    }
    if(!found) cout << "-1";
    return 0;
}
import java.util.Scanner;

public class CommonDigits {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String a = sc.next();
        String b = sc.next();
        boolean[] common = new boolean[10];
        boolean found = false;
        for(char c1 : a.toCharArray())
            for(char c2 : b.toCharArray())
                if(c1 == c2)
                    common[c1 - '0'] = true;
        for(int i = 0; i < 10; i++) {
            if(common[i]) {
                System.out.print(i);
                found = true;
            }
        }
        if(!found) System.out.print("-1");
    }
}
Previous Article

Create Number from Multiplication of Digits

Next Article

Create a Number from Non-Repeating Digits

Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *