在java中计算给定数字N中的唯一数字(例如,1091有三个唯一数字,1,0 & 9,所以函数应该返回3)。

问题描述 投票:0回答:1

给定一个数字N,例如,以1091为例,这里的数字数是4,但唯一的数字数是3,即1,0 & 9是唯一的(因为1是重复的)。

我曾试过将数字分解成单个数字,并将其添加到ArrayList中,随后将其转换为数组。然后,在数组中迭代,每当我在数组中得到一个唯一的数字时,就将唯一的数字数增加1,但我没有得到所需的输出。请大家帮忙在Java中寻找给定数字中的唯一数字计数。

import java.util.ArrayList;

public class UniqueDigits {
    static int uniqueDigitCount(int n) {
        ArrayList<Integer> ar = new ArrayList<>();
        int temp = n;
        int count = 1;
        do {
            ar.add(temp % 10);
            temp /= 10;
        }
        while (temp > 0);
        Integer[] arr = new Integer[ar.size()];
        arr = ar.toArray(arr);
        if (arr.length > 0) {
            for (int i = 0; i < arr.length - 1; i++) {
                if (arr[i] != arr[i + 1]) {

                    count++;
                }
            }
            return count;
        } else {
            return 0;
        }
    }

    public static void main(String[] args) {
        System.out.println(uniqueDigitCount(1091));
    }
}
java unique counting digits
1个回答
0
投票
import java.util.ArrayList;
import java.util.HashSet;
public class UniqueDigits {
static int uniqueDigitCount(int n) {
ArrayList<Integer> ar = new ArrayList<>();
int temp = n;
int count = 1;
do
{
ar.add(temp%10);
temp/=10;
}
while(temp>0);
Integer[] arr = new Integer[ar.size()];
arr = ar.toArray(arr);
HashSet<Integer> hs = new HashSet<Integer>();
for(int i=0; i<arr.length-1; i++) {
    hs.add(arr[i]);
}
return hs.size();
}

public static void main(String[] args)
{
System.out.println(uniqueDigitCount(1091));         
}
}

0
投票

这可以用一个集合来完成。一个集合是一个由 独一无二 元素。将所有字符(数字)放入一个集合中,将导致重复的字符被丢弃。它的 size() 然后将返回不同的元素。

使用流。

int number = 1091;
long uniques = String.valueOf(number).chars()
    .mapToObj(c -> c)
    .collect(Collectors.toSet())
    .size();

或者利用流的计数。

String.valueOf(number).chars()
    .distinct()
    .count();
© www.soinside.com 2019 - 2024. All rights reserved.