Friday, February 3, 2017

HackerRank -- count the number without repeating digits in a range



Count the number that has no repeating digits like(121,11) in a range
Given arr[][], arr[i][0]- arr[i][1] is a range.


static void countNumbers(int[][] arr) {
    Set < Integer > set = new HashSet < > ();
    for (int i = 0; i < arr.length; i++) {
        int start = arr[i][0], end = arr[i][1];
        int count = 0;
        for (int j = start; j <= end; j++) {
            if (set.contains(j)) continue;
            if (checkRepeats(j)) count++;
            else set.add(j);
        }
        System.out.println(count);
    }
}

static boolean checkRepeats(int number) {
    Set < Character > set = new HashSet < Character > (); //<digit, freq>
    String num = Integer.toString(number);
    for (Character c: num.toCharArray()) {
        if (set.contains(c)) return false;
        set.add(c);
    }
    return true;
}

No comments:

Post a Comment