删除整数中的重复数字

编程入门 行业动态 更新时间:2024-10-23 23:26:46
本文介绍了删除整数中的重复数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我已经在技术方面遇到了这个程序.他们给了我这个程序,用于删除给定整数中的重复数字,而无需使用数组或字符串.

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

更多推荐

删除整数中的重复数字

本文发布于:2023-10-25 14:12:05,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1527189.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:整数   数字

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!