I have faced this program in technical round. They have give this program to me for removing duplicate digits in given integer without using arrays or strings.
Example:
int i = 123134254;
Expected output: 12345
You can use an int
as a set to store the digits you've already encountered by assigning each digit (0,1,2,...,9) to a bit of said int
. You can then loop over the digits of i
and build a new number of solely unique digits by consulting this set. Note that I first reverse the digits of i
so I can easily loop over them in-order:
int i = 123134254;
int res = 0; // result
int set = 0; // digits we've seen
int rev = 0; // digits of `i` reversed
while (i > 0) {
rev = (rev * 10) + (i % 10);
i /= 10;
}
while (rev > 0) {
final int mod = rev % 10;
final int mask = 1 << mod;
if ((set & mask) == 0) {
res = (res * 10) + mod;
set |= mask;
}
rev /= 10;
}
System.out.println(res);
12345
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With