Removing duplicate digits in an integer [closed]

断了今生、忘了曾经 提交于 2020-02-02 03:19:18

问题


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


回答1:


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



回答2:


You could extract the digits of i using the % and / operators.

d0 = i % 10 is the LSB digit
d1 = ((i - d0) / 10) % 10 is the second digit
... and so on.

This would give you all the digits from the right to the left.

Since you are not allowed to put them in an array, lets put them in a Stack (hopefully that's allowed). This would allow you to pop them from the Stack from left to right.

For each digit you pop from the Stach, store it in a Set of duplicates, and only if it wasn't already in that Set, output it.

Now, to create output int, each time you output a digit you modify the output this way :

output = output * 10 + digit;




回答3:


1: reverse the number
2: get the last digit 1 by 1
3: check this digit with all the digits from answer
4: if no repeat found add it in answer

int i = 123134254;
int copy = 0;
while (i > 0) {
    copy = (copy * 10) + (i % 10);
    i /= 10;
}
int dig = copy % 10;
int ans = dig;
copy /= 10;
while (copy > 0) {
    boolean flag = false;
    dig = copy % 10;
    long copy2 = ans;
    while (copy2 > 0) {
        if (copy2 % 10 == dig) {
            flag = true;
            break;
        }
        copy2 /= 10;
    }
    if (!flag) {
        ans = ans * 10 + dig;
    }
    copy /= 10;
}
System.out.println(ans);


来源:https://stackoverflow.com/questions/25231218/removing-duplicate-digits-in-an-integer

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!