βœ…Common digits in two numbers (Contest)

Common digits in two numbers easy asked in interviews by 1 company Time Limit: 2 sec Memory Limit: 128000 kB

Problem Statement :

There are two number a and b are given as input. Print common digits with common index in these numbers seperated by space. Input There are two number a and b are given as input.

Constraints 1 <= a, b <= 106 Output Print common digits with common index in these numbers seperated by space. Example Sample Input: 24324345 3546434 Sample Output: 4 3 4

link:https://my.newtonschool.co/playground/code/08maf9kn577g/

import java.io.*; // for handling input/output
import java.util.*; // contains Collections framework

// don't change the name of this class
// you can add inner classes if needed
class Main {
    public static void main (String[] args) {
        Scanner sc = new Scanner(System.in);
        int a = sc.nextInt();
        int b = sc.nextInt();
        sc.close();

        String strA = String.valueOf(a);
        String strB = String.valueOf(b);

        int lenA = strA.length();
        int lenB = strB.length();
        int len = Math.min(lenA, lenB);

        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < len; i++) {
            if (strA.charAt(i) == strB.charAt(i)) {
                sb.append(strA.charAt(i));
                sb.append(" ");
            }
        }
        System.out.println(sb.toString().trim());
    }
}

Last updated