编写带有四个整数参数的方法,当且仅当四个值中至少有三个相同时才返回true

时间:2018-05-25 01:14:54

标签: boolean conditional-statements

编写方法public static boolean atLeastThreeMatch(int a, int b,int c,int d)接受四个整数参数,当且仅当四个值中至少有三个相同时才返回true。例如,如果传入的值是5,3,5,5,它将返回 真正。如果传入的值是7,3,7,9,则返回false。

为了完成任务,我编写了满足所需输出的每个可能条件。我不喜欢这样做,我觉得有一种更简单的方法来获得所需的输出。有什么想法吗?

2 个答案:

答案 0 :(得分:0)

cehck下面的代码片段,其中Set保留所有输入值。 Set仅包含不同的值,因此如果set包含小于/等于2的值,则表示至少有三个值相等。

public boolean atLeastThreeMatch(int a, int b, int c, int d) {
    List<Integer> values = Arrays.asList(a, b, c, d);
    Set<Integer> counter = new HashSet<Integer>();
    counter.addAll(values);
    if(counter.size() <=2){
        return true;
    } else {
        return false;
    }
}

答案 1 :(得分:-1)

尝试创建一个计算数字之间平等的计数器。例如:

int counter=0;
if(num1 == num2)
    counter++;

最后:

return counter==3;