Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Find numbers with same first and last digit

Sorry if I type something wrong, I am new. I want to create a method that takes an array, and gives back an array with the numbers that have the same first and last digits in the previous array.I want to use System.out in the Main(other) class.

I have created this for loop to go through the numbers, but I don’t know how to compare them.

public int[] findDuplicates(int[] a) {
      List<Integer> result = new ArrayList<>();
        for (int i = 0; i < a.length; i++) {
            for (int j = i + 1; j < a.length; j++) {
                
                if ((//what do I write here) ) {
                    //and here

                }
                
            }
        }

        return result.stream()
            .mapToInt(Integer::intValue)
            .toArray();
    }

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The easiest way is to parse your numbers into strings and compare them. I did it this way :

public int[] findDuplicates(int[] a) {
    List<Integer> result = new ArrayList<>();
    boolean[] numbersThatHaveBeenAdded = new boolean[a.length];

    for (int i = 0; i < a.length; i++) {
        for (int j = i + 1; j < a.length; j++) {

            String iNumber = String.valueOf(a[i]);
            String jNumber = String.valueOf(a[j]);
            if (iNumber.charAt(0) == jNumber.charAt(0)
                && iNumber.charAt(iNumber.length()-1) == jNumber.charAt(jNumber.length()-1)) {

                if (!numbersThatHaveBeenAdded[i]) {
                    result.add(a[i]);
                    numbersThatHaveBeenAdded[i] = true;
                }
                if (!numbersThatHaveBeenAdded[j]) {
                    result.add(a[j]);
                    numbersThatHaveBeenAdded[j] = true;
                }
            }

        }
    }

    return result.stream()
        .mapToInt(Integer::intValue)
        .toArray();
}

And I used a boolean array to keep in memory the numbers I already added in the result, to avoid duplication.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading