删除给定整数的重复数字

发布于 2025-02-04 13:29:02 字数 828 浏览 3 评论 0原文

我的结果基于以下方法,但我不满意。

我想要其他一些方式和有效的方式来获得预期的输出。

输入:

112341

输出:

1234 

不应在输出中显示重复,答案必须为1234

我的解决方案:

public class PrintUnique {
    public static void main(String[] args) {
        int result = printUniquNums(112341);
        System.out.println(result);
    }

    private static int printUniquNums(int num) {

        String nums =  Integer.toString(num);
        char [] ch = nums.toCharArray();
        Set<Character> store = new LinkedHashSet<>();

        String res = "";
        for (int i = 0; i < ch.length; i++){
            if (store.add(ch[i])){
                res += ch[i];
            }
        }
        return Integer.parseInt(res);
    }
 }

I have got my result based on below approach, but I'm not satisfied.

I want some other way and efficient manner to get the expected output.

Input:

112341

Output:

1234 

No duplicates should be displayed in output and answer must be 1234.

My solution :

public class PrintUnique {
    public static void main(String[] args) {
        int result = printUniquNums(112341);
        System.out.println(result);
    }

    private static int printUniquNums(int num) {

        String nums =  Integer.toString(num);
        char [] ch = nums.toCharArray();
        Set<Character> store = new LinkedHashSet<>();

        String res = "";
        for (int i = 0; i < ch.length; i++){
            if (store.add(ch[i])){
                res += ch[i];
            }
        }
        return Integer.parseInt(res);
    }
 }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

怀中猫帐中妖 2025-02-11 13:29:02

与Java Lambdas和Streams进行了一些调整。您的代码也很好。

public static void main(String[] args) {
        int result = printUniquNums(112341);
        System.out.println(result);
    }

    private static int printUniquNums(int num) {

        String nums =  Integer.toString(num);
        List<String> digits = List.of(nums.split(""));
        Set<String> uniqueDigits = new HashSet<>();
        String uniqueNum = digits.stream().filter(uniqueDigits::add).reduce(String::concat).orElse(""); // set add method returns true if value not present
        return Integer.parseInt(uniqueNum);
    }

A little tweaks with Java lambdas and streams. Your code is also good.

public static void main(String[] args) {
        int result = printUniquNums(112341);
        System.out.println(result);
    }

    private static int printUniquNums(int num) {

        String nums =  Integer.toString(num);
        List<String> digits = List.of(nums.split(""));
        Set<String> uniqueDigits = new HashSet<>();
        String uniqueNum = digits.stream().filter(uniqueDigits::add).reduce(String::concat).orElse(""); // set add method returns true if value not present
        return Integer.parseInt(uniqueNum);
    }
初相遇 2025-02-11 13:29:02

不使用字符串的另一种方法意味着将数字除以10,以供电数字减去一个数字,并在set set linkedhashset中从左到右收集每个数字维护插入顺序。然后,使用流来重建不重复数字的数字:

public static int uniqueNumber(int num) {
    int temp;
    Set<Integer> set = new LinkedHashSet<>();
    while (num > 10) {
        temp = (int) Math.pow(10, Math.ceil(Math.log10(num)) - 1);
        set.add(num / temp);
        num %= temp;
    }
    set.add(num);

    Integer[] digits = set.toArray(new Integer[set.size()]);
    return IntStream.range(0, digits.length)
            .map(i -> digits[i] * ((int) Math.pow(10, (digits.length - 1) - i)))
            .reduce(0, (a, b) -> a + b);
}

输出

1234

是测试代码的链接:

https://www.jdoodle.com/iembed/v0/rsi

Another approach, which doesn't use strings, implies to keep dividing the number by 10 to power the number's digits minus one and collect each digit from left to right in a Set, specifically a LinkedHashSet to maintain the insertion order. Then, using streams to rebuild the number without duplicate digits:

public static int uniqueNumber(int num) {
    int temp;
    Set<Integer> set = new LinkedHashSet<>();
    while (num > 10) {
        temp = (int) Math.pow(10, Math.ceil(Math.log10(num)) - 1);
        set.add(num / temp);
        num %= temp;
    }
    set.add(num);

    Integer[] digits = set.toArray(new Integer[set.size()]);
    return IntStream.range(0, digits.length)
            .map(i -> digits[i] * ((int) Math.pow(10, (digits.length - 1) - i)))
            .reduce(0, (a, b) -> a + b);
}

Output

1234

Here is a link to test the code:

https://www.jdoodle.com/iembed/v0/rSi

别挽留 2025-02-11 13:29:02

在性能方面,这并不是更有效的。但是,它的代码线较少,更容易阅读的行为更重要。

    private static int printUniquNums(int num) {
        TreeSet<String> tree= new TreeSet<>();
        for (char c : Integer.toString(num).toCharArray()) {
            tree.add(String.valueOf(c));
        }
        return Integer.parseInt(String.join("", tree));
    }

This is not more effecient in term of performance. But its fewer lines of code and easier to read which in most cases is more important.

    private static int printUniquNums(int num) {
        TreeSet<String> tree= new TreeSet<>();
        for (char c : Integer.toString(num).toCharArray()) {
            tree.add(String.valueOf(c));
        }
        return Integer.parseInt(String.join("", tree));
    }
一身软味 2025-02-11 13:29:02

您的方法可以使用 stream api 重新进化。

最简单的方法之一是创建一个代码点的流

然后,我们需要应用 dinters() 确保流元素的唯一性。此操作利用linkedhashset在引擎盖下拒绝重复并保留初始订单。

最后,应用终端操作 cocal> collect> collect() 代码> StringBuilder 作为A 容器用于执行可变减少的。

private static int printUniquNums(int num) {
    
    String result = String.valueOf(num).codePoints() // generating a stream of code points
        .distinct()                              // ensure uniqueness
        .collect(StringBuilder::new,             // mutable container
                 StringBuilder::appendCodePoint, // defining how values should be accumulated in the container
                 StringBuilder::append)          // how to merge the containers obtained while executing the stream in parallel
        .toString();
    
    return Integer.parseInt(result);
}

实现此目的的另一种方法是 map 流元素到string类型中,并使用内置 collector joning()< /code>将照顾AS的流串联:

private static int printUniquNums(int num) {
    
    String result = String.valueOf(num).codePoints() // generating a stream of code points
        .distinct()                      // ensure uniqueness
        .map(Character::getNumericValue) // getting a numeric value from a code point
        .mapToObj(String::valueOf)       // creating a single-character string
        .collect(Collectors.joining());  // combining the strings together
    
    return Integer.parseInt(result);
}

public static void main(String[] args) {
    int result = printUniquNums(112341);
    System.out.println(result);
}

output (对于两个解决方案):

1234

链接到在线演示

Your method can be reimplemented using Stream API.

One of the simplest ways to do it is to create a stream of code points.

Then we need to apply distinct() to insure uniqueness of the stream elements. This operation utilizes a LinkedHashSet under the hood to reject duplicates and preserve the initial order.

And finally, apply a terminal operation collect() by making use StringBuilder as a container for performing mutable reduction.

private static int printUniquNums(int num) {
    
    String result = String.valueOf(num).codePoints() // generating a stream of code points
        .distinct()                              // ensure uniqueness
        .collect(StringBuilder::new,             // mutable container
                 StringBuilder::appendCodePoint, // defining how values should be accumulated in the container
                 StringBuilder::append)          // how to merge the containers obtained while executing the stream in parallel
        .toString();
    
    return Integer.parseInt(result);
}

Another way of achieving this is to map stream elements into String type and make use of the built-in collector joning() that will take care of the stream concatenation for as:

private static int printUniquNums(int num) {
    
    String result = String.valueOf(num).codePoints() // generating a stream of code points
        .distinct()                      // ensure uniqueness
        .map(Character::getNumericValue) // getting a numeric value from a code point
        .mapToObj(String::valueOf)       // creating a single-character string
        .collect(Collectors.joining());  // combining the strings together
    
    return Integer.parseInt(result);
}

public static void main(String[] args) {
    int result = printUniquNums(112341);
    System.out.println(result);
}

Output (for both solutions):

1234

A link to Online Demo

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文