Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing duplicate digits in an integer [closed]

Tags:

java

arrays

int

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

like image 240
user3691208 Avatar asked Aug 10 '14 17:08

user3691208


1 Answers

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
like image 173
arshajii Avatar answered Sep 19 '22 16:09

arshajii