删除整数中的重复数字 [英] Removing duplicate digits in an integer
本文介绍了删除整数中的重复数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我已经在技术方面遇到了这个程序.他们给了我这个程序,用于删除给定整数中的重复数字,而无需使用数组或字符串.
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.
示例:
int i = 123134254;
预期输出:12345
推荐答案
您可以使用int
作为集合,通过分配每个数字(0、1、2,...来存储已经遇到的数字). ,9)表示int
.然后,您可以遍历i
的数字并通过参考此集合来建立新的唯一数字位数.请注意,我首先反转了i
的数字,以便可以按顺序轻松地对其进行循环:
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
这篇关于删除整数中的重复数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文