Saurabh Khare Saurabh Khare - 27 days ago 18
Java Question

Reverse Integer number without duplicate digit in java

My objective is to reverse integer number without duplicate digit in Java
How do I improve the complexity of code or is there a good/standard algorithm present?

Incase of duplicate digit, it should preserve last digit

public static void main(String[] args) {
int n = -19890;
System.out.println(reverseNumberWithoutDuplicate(n));
}

public static int reverseNumberWithoutDuplicate(int number) {
boolean isNegative = (number < 0);
number = isNegative ? number * -1 : number;

Set<Character> lookup = new HashSet<>();

StringBuffer sb = new StringBuffer();
char[] digits = String.valueOf(number).toCharArray();
for (int i = digits.length - 1; i >= 0; --i) {
if (lookup.contains(digits[i])) {
continue;
}
sb.append(digits[i]);
lookup.add(digits[i]);
}
return isNegative ? Integer.parseInt(sb.toString()) * -1 : Integer.parseInt(sb.toString());
}


Expected output: -981

Answer

The complexity is fine. Though it can be optimized.

Using StringBuilder is better than the older StringBuffer, which has unneeded overhead (for thread-safeness).

Then the data can remain numerical, and for the ten possible digits a BitSet is just fine.

public static int reverseNumberWithoutDuplicate(int number) {
    boolean isNegative = number < 0;
    number = isNegative ? -number : number;

    BitSet usedDigits = new BitSet(10);
    int reversedNumber = 0;
    while (number != 0) {
        int digit = number % 10;
        number /= 10;
        if (!usedDigits.get(digit)) {
            usedDigits.set(digit);
            reversedNumber = 10 * reversedNumber + digit;
        }
    }
    return isNegative ? -reversedNumber : reversedNumber;
}
Comments