问题
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 digitd1 = ((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